非常感谢@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
感谢目前为止所有的帮助!