我有一个用 C# 编写的 Windows 窗体应用程序,它使用 C++ 中的一个函数。这是使用 c++ 包装器完成的。但是,该函数需要使用指针,而 c# 不允许对字符串数组使用指针。可以做些什么来克服这个问题? 我已经阅读了有关使用 marshal 的内容,但我不确定这是否适合这种情况,如果适合,它应该如何与我的代码集成。 以下是C#代码:
int elements = 10;
string [] sentence = new string[elements];
unsafe
{
fixed (string* psentence = &sentence[0])
{
CWrap.CWrap_Class1 contCp = new CWrap.CWrap_Class1(psentence, elements);
contCp.getsum();
}
}
c++函数声明:
funct::funct(string* sentence_array, int sentence_arraysize)
C++ 包装器:
CWrap::CWrap_Class1::CWrap_Class1(string *sentence_array, int sentence_arraysize)
{
pcc = new funct(sentence_array, sentence_arraysize);
}
最佳答案
如果我没理解错的话,您想调用一个以字符串作为参数的 C 函数。
为此,您通常使用 PInvoke(平台调用),它使用手下的编码。
这个例子接受一个字符串并返回一个字符串。
[DllImport(KMGIO_IMPORT,CallingConvention=CallingConvention.Cdecl)]
//DLL_EXPORT ushort CALLCONV cFunction(char* sendString, char* rcvString, ushort rcvLen);
private static extern UInt16 cFunction(string sendString, StringBuilder rcvString, UInt16 rcvLen);
public static string function(string sendString){
UInt16 bufSize = 5000;
StringBuilder retBuffer = new StringBuilder(bufSize);
cFunction(sendString, retBuffer, bufSize);
return retBuffer.ToString();
}
关于c# - c#中的字符串指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19969690/