从C#传递字符串,以C ++ DLL和背部 - 小例子, [英] Passing strings from C# to C++ dll and back -- minimal example
问题描述
我试图使绝对简单的如何串传入和从C#中的C ++的dll小例子。
I am trying to make the absolute simplest minimal example of how to pass strings to and from a C++ dll in c#.
我的C ++看起来是这样的:
My C++ looks like this:
using std::string;
extern "C" {
string concat(string a, string b){
return a + b;
}
}
有了这样一个标题
With a header like
using std::string;
extern "C" {
// Returns a + b
__declspec(dllexport) string concat(string a, string b);
}
我的C#是
[DllImport("*****.dll", CallingConvention = CallingConvention.Cdecl)]
static extern string concat(string a, string b);
}
和我与调用它:
Console.WriteLine(CONCAT(一,B));
And I am calling it with: Console.WriteLine(concat("a", "b"));
但是,这给出了一个System.AccessViolationException。这似乎是它是最琐碎的事情来处理,但我完全被卡住就可以了。当我试图做一个类似的实验与函数添加这花了两个双打和返回的双重我没有问题。
But this gives a System.AccessViolationException. This seems like it out to be the most trivial thing to deal with but I am completely stuck on it. When I tried to do a similar experiment with a function "Add" that took two doubles and returned a double I had no problems.
帮助是极大的pciated !! AP $ P $
Help is greatly appreciated!!
推荐答案
您不能跨边界的互操作传递一个C ++ 的std ::字符串
。您不能创建那些在您的C#code之一。所以,你的code不能正常工作。
You cannot pass a C++ std::string
across an interop boundary. You cannot create one of those in your C# code. So your code can never work.
您需要在互操作界面使用互操作友好的类型。例如,空值终止字符数组。当你分配和释放在同一个模块在内存中运行良好。所以,这是很简单的从C#传递数据时,C ++。
You need to use interop friendly types at the interop boundary. For instance, null-terminated arrays of characters. That works well when you allocate and deallocate the memory in the same module. So, it's simple enough when passing data from C# to C++.
C ++
void foo(const char *str)
{
// do something with str
}
C#
[DllImport("...", CallingConvention = CallingConvention.Cdecl)
static extern void foo(string str);
....
foo("bar");
在其他方向,你会通常希望调用者分配的缓冲区,在其中被叫方可以这样写:
In the other direction you would typically expect the caller to allocate the buffer, into which the callee can write:
C ++
void foo(char *str, int len)
{
// write no more than len characters into str
}
C#
[DllImport("...", CallingConvention = CallingConvention.Cdecl)
static extern void foo(StringBuilder str, int len);
....
StringBuilder sb = new StringBuilder(10);
foo(sb, sb.Capacity);
这篇关于从C#传递字符串,以C ++ DLL和背部 - 小例子,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!