C#调用C++的dll,返回空字符串,求助

hanfaye 2005-09-07 10:36:57
C++的Dll
extern "C" __declspec(dllexport)
bool __cdecl GetResult(int value1,unsigned char * value2)
{
if (value1)
FuncA(value2);
else
FuncB(value2);

return true;
}

void FuncA(unsinged char* value)
{
....
}

void FuncB(unsigned char* value)
{
...
}

C#里调用
string strValue;
int iCount;
GetResult(iCount,ref strValue);//不用ref也是返回空值
得到的strValue为空值,请问,Dll里应该怎样定义传入的参数,才能返回字符串给C#?

...全文
222 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
hanfaye 2005-09-08
  • 打赏
  • 举报
回复
问题还没有解决。。。

昨天没有把每个函数都描述得很清楚。

其中,FuncA的定义是
FuncA( CONNECTION_HANDLE hConnection,
const char* pchSendBuffer, // command to send
unsigned long ulSendBufferLen,// command length
unsigned char uchDeviceID,// device id
int iCmdDataMode, // command data mode
unsigned char* pchRcvBuffer, // buffer to store response
//这里的pchRcvBuffer就是我想返回给C#的值
unsigned long ulRcvBufferSize,// size of buffer to store response
unsigned long ulTimeout, // timeout in milliseconds
unsigned long* pulNumBytesRcved,// out param - number of bytes received
unsigned long* pulStatusCode // out param - device status code
);

当C#调用Dll中的GetResult时(参数定义上面已说明),
bool bSend=SendCommand(
CONNECTION_HANDLE,
command,
out receiveBuffer,
//这里无论用out/ref string/StringBuilder,当FuncA里的pchRcvBuffer有返回值时,
//C#就会出现一个NullReferenceExcpetion.
//当pchRcvBuffer没有返回值时,就不会出错。
ref bytesReceived,
ref statusCode);
真相重于对错 2005-09-08
  • 打赏
  • 举报
回复
ref stringbuilder//注意大小写
暗石绿 2005-09-08
  • 打赏
  • 举报
回复
static extern bool GetResult(int value1, byte[] value2);

如果这个不行的话,就试试

static extern bool GetResult(int value1,ref byte[] value2);

lovevsnet 2005-09-08
  • 打赏
  • 举报
回复
[DllImport("xxx.dll", CharSet = CharSet.Auto)]
static extern bool GetResult(int iCount, [In,Out]string strValue);
-------------------------------------------------------------------
[DllImport("xxx.dll", CharSet = CharSet.Auto)]
static extern bool GetResult(int iCount,[MarshalAs(UnmanagedType.LPWStr)] string strValue);
------------------------------------------------------------------------
试试行不行?
不行改用,[MarshalAs(UnmanagedType.LPWStr)] ref string
wuyi8808 2005-09-07
  • 打赏
  • 举报
回复
在函数声明的 ref 前面加上 [in] [out] 属性试试:

[DllImport("xxx.dll", CharSet = CharSet.Auto)]
static extern bool GetResult(int iCount, [in] [out] ref string strValue);

110,545

社区成员

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

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

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