C#中如何调用C++生成DLL的unsigned char*,unsigned int*参数

oniman123 2013-09-23 12:26:59
问题说明:

C++DLL 函数声明是

DWORD CalcSign(unsigned char* pData,
unsigned int nSize,
unsigned char* pOutData,
unsigned int* nOutSize);


pData和nSize为输入参数,pOutData和nOutSize为输出参数

问题是在C#中如何调用这个C++写的DLL的函数?

我自己尝试的方法:
首先声明使用
[DllImport("cplus.dll", CallingConvention = CallingConvention.Cdecl)]
unsafe public static extern uint CalcSign(
byte* pCertData, int nSize,
byte* pSignSapData, ref int nOutSize
);

其中比较不清楚的是unsigned int* 是不是能用ref uint代替

这个是将C#中的string变成byte*类型
private static unsafe byte* toBytes(string str)
{
byte[] mt = Encoding.Default.GetBytes(str);
fixed (byte* result = mt)
{
return result;
}
}


然后我调用的方法如下

string inputData = ".....";
int inputDataLen = Encoding.ANSCII.GetBytes(inputData).Length;
string outputData = new string[9999];
int outputDataLen = Encoding.ANSCII.GetBytes(outputData).length;

CalcSign(toBytes(inputData), inputDataLen, toBytes(outputData), ref outputDataLen)

调用之后报Exception,
{System.AccessViolationException: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏}

请教我该如何正确调用这个方法!非常感谢!
...全文
842 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Kenall 2013-09-23
  • 打赏
  • 举报
回复
[DllImport("cplus.dll", CallingConvention = CallingConvention.Cdecl)]
        unsafe public static extern uint CalcSign(
                       ref byte pCertData, uint nSize,
                       ref byte pSignSapData, ref int nOutSize
            );
把unsign char * 转成 ref byte试试看
bdmh 2013-09-23
  • 打赏
  • 举报
回复
ref xxxxx
chinaheart88 2013-09-23
  • 打赏
  • 举报
回复
右键->引用
gomoku 2013-09-23
  • 打赏
  • 举报
回复
用byte[]比较简单:
static extern uint CalcSign(byte[] pCertData, int nSize, byte[] pSignSapData, ref int nOutSize);

//调用时,要准备pSignSapData:
int size = 1024;
byte[] data = new byte[size];
CalcSign(..., data, ref size);
另,你的unsafe byte* toBytes(string str)函数有问题(出了fixed范围后,得到的指针就不安全了)。
oniman123 2013-09-23
  • 打赏
  • 举报
回复
一个更简单的方法 C++里面的函数声明是 DWORD CalcGuid(void* pGuid); 我要怎么调用呢?是这样吗? [DllImport("cplus.dll", CallingConvention = CallingConvention.Cdecl)] unsafe public static extern uint CalcGuid(IntPtr pGuid); IntPtr mm = new IntPtr(200); uint calResult = CalcGuidEx(mm);
oniman123 2013-09-23
  • 打赏
  • 举报
回复
不行~~直接就没反应。

110,533

社区成员

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

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

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