c# - c#中的字符串指针

标签 c# pointers

我有一个用 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/

相关文章:

c# - Xamarin.iOS MKLaunchOptionsDirectionsModeKey

c# - MVVM 基本内容控件绑定(bind)

C++ 抛出未知异常类型,但仅在生产构建中

c - 在两个增量和间接运算符的情况下,C 如何处理运算优先级?

c++ - 为什么 *ptr++ 不改变指针对象的值,而 (*ptr)++ 改变指针对象的值?

c# - 在 C# 中编码 C++ .dll

c# - 无效的资源目录名称: “res animation” aapt.exe

c# - Thread.Abort() 导致应用程序被杀死

c - 赋值和指针,未定义的行为?

c:将 const char* 读入 sscanf 中的变量?