views:

485

answers:

3

I wrote a C# application that uses an unmanaged c++ dll via managed c++ dll. In the unmanaged dll, there's a callback that one of its params is std::string &.

I can't seem to find the right way to wrap this with the managed dll. When I use String ^, the callback works, but the C# application does not get anything in the string. When I used String ^%, things started to crash in other places that does not seem to be related (maybe memory corruption).

So my question is, what's the right way to do this?

Thanks

A: 

Posting some code would help me understand better and give a better answer; but there is no automatic conversion or marshalling of String^ to std::string. You would need to do to marshalling yourself to get the string back to the C# code. A quick search can provide with details on how to do this.

http://msdn.microsoft.com/en-us/library/42zy2z41.aspx

Ian Gibson
A: 

I can't copy-paste code here, but I'll try to explain again. I can't use marshaling in the managed c++ section because I'm not calling a function, but passing a c# delegate for a callback.

In the unmanaged dll, I have a callback that requires a function like this: void Func(unsigned int, int, std:string &).

My goal is to pass a c# delegate from my program to that callback, so in the unmanaged code, I made a delegate like this: delegate void DEL(unsigned int a, int b, String ^ c) and a function like: void mFunc(DEL ^ del), and that function marshal's the delegate into a cb that the unmanaged callback subscribe function accepts. The unsigned int and int works fine, but the string is always "" when the C# function is triggered.

Elad
A: 

I don't believe that the marshalling can deal with std::string. I think you need to make your own callback that passes char * and then write the glue code between the two.

Also, once the delegate is marshalled into a callback, that callback does not count as a reference to the object that the delegate might have been made from. So if the delegate is not a static method, you need to stuff it somewhere for the lifetime of the unmanaged callback.

Lou Franco