gpt4 book ai didi

c# - 将字符指针从 C# 传递到 C++ 函数

转载 作者:太空狗 更新时间:2023-10-29 21:07:48 24 4
gpt4 key购买 nike

我被困在 C# 实现方面,因为我对它还很陌生。问题是,我想从 c# 代码传递一个“指针”(具有内存),以便我的 c++ 应用程序可以将 pchListSoftwares 缓冲区复制到 pchInstalledSoftwares。我无法弄清楚如何从 C# 端传递指针。

原生c++代码(MyNativeC++DLL.dll)

void GetInstalledSoftwares(char* pchInstalledSoftwares){
char* pchListSoftwares = NULL;
.....
.....
pchListSoftwares = (char*) malloc(255);

/* code to fill pchListSoftwares buffer*/

memcpy(pchInstalledSoftwares, pchListSoftwares, 255);

free(pchListSoftwares );

}

传递简单的“字符串”是行不通的...

C#实现

[DllImport("MyNativeC++DLL.dll")]
private static extern int GetInstalledSoftwares(string pchInstalledSoftwares);


static void Main(string[] args)
{
.........
.........
string b = "";
GetInstalledSoftwares(0, b);
MessageBox.Show(b.ToString());
}

非常感谢任何形式的帮助...

最佳答案

尝试使用 StringBuilder

[DllImport("MyNativeC++DLL.dll")]
private static extern int GetInstalledSoftwares(StringBuilder pchInstalledSoftwares);


static void Main(string[] args)
{
.........
.........
StringBuilder b = new StringBuilder(255);
GetInstalledSoftwares(0, b);
MessageBox.Show(b.ToString());
}

关于c# - 将字符指针从 C# 传递到 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4385783/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com