gpt4 book ai didi

c# - 在 c# dll 和 c++ dll 之间传递字符串变量作为引用

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:58:14 25 4
gpt4 key购买 nike

我有一个 c# dll 和一个 c++ dll。我需要将一个字符串变量作为引用从 c# 传递到 c++ 。我的 c++ dll 将用数据填充变量,我将在 C# 中使用它,我该怎么做。我尝试使用引用。但是我的 c# dll 抛出异常。 “试图读取或写入 protected 内存。......这通常表明其他内存已损坏”。关于如何做到这一点的任何想法

最佳答案

作为一般规则,您使用 StringBuilder 作为引用或返回值,使用 string 作为您不想/不需要在 DLL 中更改的字符串。

StringBuilder对应LPTSTRstring对应LPCTSTR

C# 函数导入:

[DllImport("MyDll.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static void GetMyInfo(StringBuilder myName, out int myAge);

C++代码:

__declspec(dllexport) void GetMyInfo(LPTSTR myName, int *age)
{
*age = 29;
_tcscpy(name, _T("Brian"));
}

调用函数的C#代码:

StringBuilder name = new StringBuilder(512);
int age;
GetMyInfo(name, out age);

关于c# - 在 c# dll 和 c++ dll 之间传递字符串变量作为引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2417494/

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