简体   繁体   English

互操作将字符串从C#发送到C ++

[英]Interop sending string from C# to C++

I want to send a string from C# to a function in a native C++ DLL. 我想将字符串从C#发送到本机C ++ DLL中的函数。

Here is my code: The C# side: 这是我的代码:C#端:

[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: C ++方面:

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

What I get in the C++ side is an empty string, every time, no matter what I send. 无论我发送什么,我每次在C ++端得到的都是一个空字符串。 Help? 救命?

Thanks. 谢谢。

Works fine for me with no extra marshalling instructions in VS2008: 在VS2008中无需额外的编组说明,对我来说工作正常:

C# side: C#端:

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

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

C++ side: C ++方面:

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

It looks like you have 2 issues. 看来您有2个问题。 The first is your native C++ uses an ANSI string but you are specifying unicode. 第一个是您的本机C ++使用ANSI字符串,但是您要指定unicode。 Secondly, it's easiest to just marshal a string as a string. 其次,仅将字符串编组为字符串是最简单的。

Try changing the DllImport to the following 尝试将DllImport更改为以下内容

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

Your declaration is wrong. 您的声明是错误的。 The parameter should be of type string, and you should set the character set encoding to Ansi, like so: 该参数应为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 your C++ code. 这假定您没有在C ++代码中修改path变量的内容。 Then, you pass the string parameter directly (no need for the wrapper). 然后,您直接传递string参数(不需要包装器)。

If you just want to send a string, just declare func1's parameter as a string. 如果只想发送字符串,则只需将func1的参数声明为字符串。 If you want to receive a string, declare it as a StringBuilder and allocate enough buffer space for what you want to receive. 如果要接收字符串,则将其声明为StringBuilder并为要接收的内容分配足够的缓冲区空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM