Interop sending string from C# to C++

心不动则不痛 提交于 2019-12-17 21:32:19

问题


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.


回答1:


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);



回答2:


Works fine for me with no extra marshalling 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");
}



回答3:


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).




回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/683013/interop-sending-string-from-c-sharp-to-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!