views:

713

answers:

5

Duplicate of http://stackoverflow.com/questions/683013/interop-sending-string-from-c-to-c

I want to send a string from C# to a function in a native C++ DLL.

Here is my code:

The C# side:

[DllImport(@"Native3DHandler.dll", EntryPoint = "#22", CharSet = CharSet.Unicode)]
private static extern void func1(string str);

public void func2(string str)
{
   func1(str);
}

The C++ side:

void func1(wchar_t *path)
{
    //...
}

What I get in the C++ side is an empty string, every time, no matter what I send. Help?

I already asked it here before, but I didn't get an answer that worked.

Thanks.

A: 

Look here -> http://stackoverflow.com/questions/683013/interop-sending-string-from-c-to-c

hope it helps

Petoj
that's the posters' original question!
Mitch Wheat
A: 

Try to put

MarshalAs(UnmanagedType.BStr)

for string type that you are passing to method.

Vinay
A: 

You should declare your C++ func like this: extern "C" void __stdcall func1(wchar_t *path)

If that doesn't help, try passing a StringBuilder instead of a string.

(Disclaimer: I've never actually passed Unicode code strings, so if neither of the above suggestions work, then just a a test, you could try with "Ansi" instead just to see what happens.)

danbystrom
+1  A: 

You need

[DllImport(@"Native3DHandler.dll", EntryPoint = "#22", CharSet = CharSet.Unicode)]
private static extern void func1 ([MarshalAs (UnmanagedType.LPWSTR)] string str) ;

in this case (wchar_t*). And pay attention to the calling convention, as @danbystrom suggests.

Anton Tykhyy
A: 

have you read this ?

Default Marshaling for Strings

http://msdn.microsoft.com/en-us/library/s9ts558h(VS.71).aspx

iterationx