简体   繁体   English

在C#中使用cpp代码(返回自定义结构和std:string)

[英]Using cpp code in c# (return custom struct and std:string)

I'm trying to build a wrapper to use cpp code inside c# code, and I want to return custom struct (Class) as output for method2, and std::string for method1, and this is my code in cpp 我正在尝试构建一个包装程序以在c#代码中使用cpp代码,并且我想返回自定义结构(类)作为method2的输出,并返回std :: string作为method1的输出,这是我在cpp中的代码

extern "C" __declspec(dllexport)  std::string method1()
{
  std::string s;
  //Some Code/////////
  return s;
}

and this is the method that should return custom struct (or class) 这是应该返回自定义结构(或类)的方法

extern "C" __declspec(dllexport)  MyStruct method2()
{
  MyStruct s;
  //Some Code//////
  return s;
}

and I tried to write c# code for both of these methods and here is my c# code 我试图为这两种方法编写C#代码,这是我的C#代码

[DllImport("<dllPath>", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.LPStr)]
public static extern string  method1(); //Exception

[DllImport("<DllPath>")]
public static extern MyStruct method2(); //Compile Error

Now when I'm trying to run the c# code I get MarshalDirectiveException for method1, and compiling error for method2? 现在,当我尝试运行C#代码时,方法1出现MarshalDirectiveException,而方法2出现编译错误?

In the first PInvoke, the C++ method should return const char* (s.c_str()). 在第一个PInvoke中,C ++方法应返回const char *(s.c​​_str())。 You should remove "[return [...]]" and replace string by IntPtr. 您应该删除“ [return [...]]”,然后将字符串替换为IntPtr。 Then, you can convert the IntPtr to string with Marshal.PtrToStringAnsi(ptr). 然后,您可以使用Marshal.PtrToStringAnsi(ptr)将IntPtr转换为字符串。 http://msdn.microsoft.com/en-US/library/s9ts558h(v=vs.110).aspx can help you. http://msdn.microsoft.com/zh-CN/library/s9ts558h(v=vs.110).aspx可以为您提供帮助。

In the second PInvoke, you should define in C# the MyStruct (but I can't be more precise because I have no information about MyStruct). 在第二个PInvoke中,您应该在C#中定义MyStruct(但是我不能更精确,因为我没有有关MyStruct的信息)。 This link can help you : http://www.codeproject.com/Articles/66243/Marshaling-with-C-Chapter-Marshaling-Compound-Ty 该链接可以为您提供帮助: http : //www.codeproject.com/Articles/66243/Marshaling-with-C-Chapter-Marshaling-Compound-Ty

EDIT : Thanks to hvd's comment, it is better sometimes to use BSTR , because the use of char* can be dangerous ! 编辑:感谢hvd的评论,有时最好使用BSTR ,因为使用char *可能很危险!

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

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