问题描述
我尝试不同的事情,但我越来越疯狂与互操作。
I tried different things but i'm getting mad with Interop.
(这里字串不称为一个variabile的类型,但集合炭):
我有一个非托管C ++函数,在DLL中定义的,我试图从C#访问,这个功能有一个字符串参数,像这样的字符串返回值:
(here the word string is not referred to a variabile type but "a collection of char"):I have an unmanaged C++ function, defined in a dll, that i'm trying to access from C#, this function has a string parameter and a string return value like this:
string myFunction(string inputString)
{
}
应该是什么的字符串在C ++中的一面呢?和C#的?什么参数需要的DllImport此?
What should be string in C++ side? and C# one? and what parameters need DllImport for this?
推荐答案
我已经找到了最好的工作是要更加明确什么是怎么回事。有一个字符串返回类型可能不是在这种情况下建议。
What I've found to work best is to be more explicit about what's going on here. Having a string as return type is probably not recommended in this situation.
一个普通的方法是有C ++的侧传递缓冲器和缓冲器大小。如果不是为了什么的GetString已摆在它足够大,缓冲区大小变量被修改,以表明合适的大小将是什么。然后调用程序(C#)将增加缓冲器的大小,以适当的大小。
A common approach is to have the C++ side be passed the buffer and buffer size. If it's not big enough for what GetString has to put in it, the bufferSize variable is modified to indicate what an appropriate size would be. The calling program (C#) would then increase the size of the buffer to the appropriate size.
如果这是你导出的DLL函数(C ++):
If this is your exported dll function (C++):
extern "C" __declspec void GetString( char* buffer, int* bufferSize );
匹配C#是以下内容:
Matching C# would be the following:
void GetString( StringBuilder buffer, ref int bufferSize );
因此,要使用这个在C#中,你会做一些这样的:
So to use this in C# you would then do something like the following:
int bufferSize = 512;
StringBuilder buffer = new StringBuilder( bufferSize );
GetString( buffer, ref bufferSize );
这篇关于通C#字符串到C ++,并通过C ++的结果(字符串,字符* ...等等)到C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!