gpt4 book ai didi

c# - 将 char * 从 C# 字符串传递到 C DLL

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

我需要在 C# 应用程序的 DLL 中使用 C 函数库。我在使用 char * 参数调用 DLL 函数时遇到问题:

C DLL:

extern "C" __declspec(dllexport) int CopyFunc(char *, char *);
int CopyFunc(char *dest, char *src)
{
strcpy(dest, src);
return(strlen(src));
}

C# 应用程序需要看起来像这样:

[DllImport("dork.dll")]
public static extern int CopyFunc(string dst, string src);

int GetFuncVal(string source, string dest)
{
return(CopyFunc(dest,source));
}

我见过使用字符串或 StringBuilder 或 IntPtr 替换 DLL 函数原型(prototype)所需的 char * 的示例,但我无法使它们中的任何一个工作。我得到的最常见的异常是 PInvoke 正在使堆栈不平衡,因为函数调用与原型(prototype)不匹配。

有没有简单的解决方法?

最佳答案

像这样更新外部函数的 P/Invoke 声明:

[DllImport("dork.dll")]
public static extern int CopyFunc([MarshalAs( UnmanagedType.LPStr )]string a, [MarshalAs( UnmanagedType.LPStr )] string b);

int GetFuncVal(string src, string dest)
{
return(CopyFunc(dest,src));
}

关于c# - 将 char * 从 C# 字符串传递到 C DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39987435/

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