vb调用C语言dll中char,c++ - 如何正确使用intptr将c * DLL中的char *值返回给Vb.net - 堆栈内存溢出...

非常感谢@Remy Lebeau。 我已经尝试实现CoTaskMemAlloc()方法,它的工作原理! 我的代码如下:

在cpp文件中,我编辑了使用CoTaskMemAlloc()分配的返回值

char* CPMfn(char* sdatabase, int project_num)

{

/* Retrieve data from database and calculate CPM for the selected project number*/

char* CPMvector = getCPM(sdatabase, project_num);

/* Store results in specially allocated memory space that can easily be deallocated when this DLL is called*/

ULONG ulSize = strlen(CPMvector) + sizeof(char);

char* ReturnValue = NULL;

ReturnValue = (char*)::CoTaskMemAlloc(ulSize);

// Copy the contents of CPMvector

// to the memory pointed to by ReturnValue.

int charlen = strlen(CPMvector);

strcpy_s(ReturnValue, charlen + 1, CPMvector);

// Return

return ReturnValue;

}

在VB.net文件中,我编写了Dllimport和编组代码,如下所示:

'' Import C++ CPM Calculation function from CPM DLL

Private Shared Function CPMfn(ByVal dbstring As String, ByVal task As Int32) As String

End Function

'' Get CPM results from DLL function

Dim teststring As String = CPMfn(cDBString, Val(Project_IDTextBox.Text))

或者我也尝试使用GlobalAlloc()和Marshal.FreeHGlobal()函数手动释放分配的内存,但我得到相同的结果(即第一次调用= 1,2,3 \\ n,第二次调用= 1, 2,3 \\ n,4,5,6 \\ n而不仅仅是4,5,6 \\ n)。

这是我使用GlobalAlloc()方法的代码:

在.cpp文件中

ReturnValue = (char*)::GlobalAlloc(GMEM_FIXED, ulSize);

strcpy_s(ReturnValue, strlen(CPMvector) + 1, CPMvector);

并在VB.net文件中

Private Shared Function CPMfn(ByVal dbstring As Char(), ByVal task As Int32) As System.IntPtr

End Function

Dim CPMresults As IntPtr = CPMfn(cDBString, Val(Project_IDTextBox.Text))

Dim CPMvalues As String = Marshal.PtrToStringAnsi(CPMresults)

Marshal.FreeHGlobal(CPMresults)

CPMresults = IntPtr.Zero

感谢目前为止所有的帮助!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值