繁体   English   中英

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

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

我正在尝试构建一个包装程序以在c#代码中使用cpp代码,并且我想返回自定义结构(类)作为method2的输出,并返回std :: string作为method1的输出,这是我在cpp中的代码

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

这是应该返回自定义结构(或类)的方法

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

我试图为这两种方法编写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

现在,当我尝试运行C#代码时,方法1出现MarshalDirectiveException,而方法2出现编译错误?

在第一个PInvoke中,C ++方法应返回const char *(s.c​​_str())。 您应该删除“ [return [...]]”,然后将字符串替换为IntPtr。 然后,您可以使用Marshal.PtrToStringAnsi(ptr)将IntPtr转换为字符串。 http://msdn.microsoft.com/zh-CN/library/s9ts558h(v=vs.110).aspx可以为您提供帮助。

在第二个PInvoke中,您应该在C#中定义MyStruct(但是我不能更精确,因为我没有有关MyStruct的信息)。 该链接可以为您提供帮助: http : //www.codeproject.com/Articles/66243/Marshaling-with-C-Chapter-Marshaling-Compound-Ty

编辑:感谢hvd的评论,有时最好使用BSTR ,因为使用char *可能很危险!

暂无
暂无

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

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