【发布时间】:2015-06-23 09:21:43
【问题描述】:
我有一个第三方库,它有一个类,其中构造函数采用std::wstring。
构造函数由第三方在头文件中这样定义:
Something(const std::wstring &theString);
我的头文件有这个:
extern "C" __declspec(dllexport) ThirdParty::Something* createSomething(const std::wstring &theString);
我的实现是这样的:
ThirdParty::Something* Bridge::createSomething(const std::wstring &theString) {
return new ThirdParty::Something(theString);
}
现在在我的 C# 示例程序中,我有:
[DllImport("Bridge.dll", CallingConvention=CallingConvention.StdCall, CharSet=CharSet.Unicode)]
public static extern IntPtr createSomething(StringBuilder theString);
当我现在尝试这样称呼时:
IntPtr ip = createSomething(new StringBuilder("foo"));
我收到了AccessViolationException。当我使用String 而不是StringBuilder 时,我得到一个SEHException。
我遗漏了什么或做错了什么?
编辑当我在createSomething 函数中只使用return 0 时,我在使用String 时得到一个StackImbalanceException。
【问题讨论】:
-
您需要一些 C++/CLI 和/或一些纯 C++(您可以选择)。您不能从 C# 创建 C++ 对象。
-
我尝试按照本教程进行操作:codeproject.com/Articles/18032/How-to-Marshal-a-C-Class,他们在那里做我正在尝试的事情。
-
一般来说,与第三方 C++ 库的链接是一团糟……如果你使用相同的编译器和 C++ 库的相同选项,那么就没有问题……否则就是糟糕...
-
该教程不会创建
std::string或std::wstring。而且这两种解决方案都需要创建一个 C/C++ 桥,其中桥不接受 C++ 对象...
标签: c# c++ string interop marshalling