请问C#调用C的DLL函数

pinel 2008-04-01 05:30:26
函数如下
extern "C" _declspec(dllexport) char* __stdcall myfunction(const char* keyfile,const char* in_str, int* out_len);

我在C#工程里添加
using System.Runtime.InteropServices;
[DllImport("mydll.dll",CharSet=CharSet.Ansi, CallingConvention=CallingConvention.StdCall)]

IntPtr len=new IntPtr(10);
System.String ret=DecPn("test1", "test2", len);


编译报错:尝试读取或写入受保护的内存。这通常指示其他内存已损坏

...全文
93 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
hanjun1024 2008-04-02
  • 打赏
  • 举报
回复
你先确定分配内存由哪边来执行。问题可能出在返回值那里,试试看这样定义。

[DllImport("mydll.dll",CharSet=CharSet.Ansi)]
public static extern IntPtr myfunction(string keyfile, string inStr, ref int len);

int len;
IntPtr ret = myfunction("test1", "test2", ref len);

string result = Marshal.PtrToStringAnsi(ret);



可能有的问题是不能显式释放内存。
pinel 2008-04-02
  • 打赏
  • 举报
回复
我改成如下几种方式,仍然报同样的错,不知道问什么,高手请帮忙啊
public static extern StringBuilder myfunction(String keyfile, String in_str, out int out_len);

int len=0;
StringBuilder ret = new StringBuilder();
ret = DecPn("test1", "test2", out len);

最后一个参数改成ref int 或IntPtr都没用...

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧