views:

731

answers:

7

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(byte[] path);

public void func2(string path)
{
   ASCIIEncoding encoding = new ASCIIEncoding();
   byte[] arr = encoding.GetBytes(path);
   func1(this.something, arr);
}

The C++ side:

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

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

Thanks.

A: 

Oops, please ignore the fact that I send 2 parameters and only recieve one. That was a copying mistake.

You can always edit your own posts
Eric
+1  A: 

It looks like you have 2 issues. The first is your native C++ uses an ANSI string but you are specifying unicode. Secondly, it's easiest to just marshal a string as a string.

Try changing the DllImport to the following

[DllImport(
  @"Native3DHandler.dll", 
  EntryPoint = "#22",  
  CharSet = CharSet.Ansi)]
private static extern void func1(void* something, [In] string path);
JaredPar
A: 

Your declaration is wrong. The parameter should be of type string, and you should set the character set encoding to Ansi, like so:

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

This assumes that you are not modifying the contents of the path variable in your C++ code. Then, you pass the string parameter directly (no need for the wrapper).

casperOne
A: 

If you just want to send a string, just declare func1's parameter as a string. If you want to receive a string, declare it as a StringBuilder and allocate enough buffer space for what you want to receive.

danbystrom
A: 

@JaredPar: I tried what you suggested, and it still gives me an empty string on the C++ side.

Can you edit your post to include the actual C++ signature? Also why do you have EntryPoint the way it is? Usually you can just ignore that
JaredPar
A: 

@casperOne: Same deal, I get an empty string.

A: 

Default Marshaling for Strings http://msdn.microsoft.com/en-us/library/s9ts558h.aspx

iterationx