Interaction of sending a string from C # to C ++

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

Here is my code: 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);
}

C ++ side:

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

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

Thank.

+2
source share
5 answers

It looks like you have 2 problems. First, your native C ++ uses the ANSI string, but you specify unicode. Secondly, the easiest way is to simply arrange the string as a string.

Try changing DllImport to the next

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

Works great for me without additional sorting instructions in VS2008:

C # side:

[DllImport("Test.dll")]
public static extern void getString(StringBuilder theString, int bufferSize);

func()
{
  StringBuilder tstStr = new StringBuilder(BufSize);
  getString(tstStr, BufSize);
}

C ++ side:

extern "C" __declspec(dllexport) void getString(char* str, int bufferSize)
{
  strcpy_s(str, bufferSize, "FOOBAR");
}
+2
source

. string, Ansi, :

[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 C ++ code. Then you pass the string parameter directly (no wrapper needed).

0
source

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

0
source

By default, marshaling for strings is http://msdn.microsoft.com/en-us/library/s9ts558h.aspx

0
source

All Articles