Re: C# System.String parameter passed into an unmanaged C++ DLL
Thanks, Night Wulfe.
So, my original claim was incorrect - the DLL *IS* being compiled with /clr. So, given that, any suggestions how I can just pass a string down to it?
I've posted a zip in one of the above posts with a simple sample project containing both a DLL and an application just like I've got showing the exact issue.
Thanks again.
Re: C# System.String parameter passed into an unmanaged C++ DLL
Oh I see. The problem is you're trying to pass a string type to a char* (sbyte* to C#) type. These types are incompatible. There are two ways around this:
1) If you'd rather use the string type in C++ like you do C#, change your C++ DLL to take a type of System::String^ instead of char*. This will also require you to change your check against 0x00 (for null) to "nullptr" (without the quotes).
2) Alternatively, you'll have to proceed down the marshaling route mentioned before and/or use "unsafe" code blocks to get a byte array pointer to the string. This will probably require a call to System.Text.Encoding.ASCII.GetBytes.
Re: C# System.String parameter passed into an unmanaged C++ DLL
Ok, so this has been a learning experience but I'll share how I've solved the issue in case anyone wanders into this thread. Of course, this is going to be pretty obvious to most people. It's certainly pretty obvious to me now. Live and learn.
Since the DLL I was calling into from C# was compiled /clr that means that I have access to the same basic data types in the C++ DLL code as I do in the C# app code. Thus, where I had:
MyClass:bool Foo( char* str);
I changed to:
MyClass:bool Foo( String ^str);
...and everthing magically worked.
If I didn't have access to the C++ DLL source code, I would have had to write, as Night Wulfe suggested, s C++/CLI wrapper around the native code.
Thanks for all the help, especially the links to learn more.
Re: C# System.String parameter passed into an unmanaged C++ DLL
Night Wulfe, our posts passed in the ether. Thanks. I just figured out the solution you suggested.
Thanks again for the help.
Re: C# System.String parameter passed into an unmanaged C++ DLL
In my opinion you are mismatching native vs. managed types and making your life more difficult.
If you are creating a managed C++ assembly to be used in a .Net application, then make your life easier by using managed types in the public methods.
So in your case, prototype Foo2 as:
Code:
bool Foo2( String^ str );
That way, you can simply pass it a System.String object in the calling assembly:
Code:
String str = "Test Me!";
myclass.Foo2( str );