我在C#中调用了名为“GenerateCode”的C ++函数来获取指向内存块的指针(从“new”运算符返回)。在C#中使用后,应该释放内存块。 但我尝试了Marshal.FreeHGlobal(),它总是抛出异常。 而且,我写了一个C ++函数来释放内存,它总是抛出异常。 我不知道该怎么做。
C#代码
[DllImport("Generate.dll", EntryPoint = "GenerateCode", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr GenerateCode([MarshalAs(UnmanagedType.LPStr)]string ComputerInfo, string ProductKey);
[DllImport("Generate.dll", EntryPoint = "FreeMemory", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern void FreeMemory(IntPtr ptr);
public string GetRegisterCode(string ComputerInfo, string ProductKey)
{
string s = null;
IntPtr ptr = new IntPtr();
ptr = GenerateCode(ComputerInfo, ProductKey);
s = Marshal.PtrToStringAnsi(ptr, CODE_LENGTH);
FreeMemory(ptr);
}
C ++代码:
const int LENGTH = 24;
extern "C" __declspec(dllexport) char* GenerateCode(char* ComputerInfo, char* ProductKey)
{
char* strAsciiName = new char[LENGTH];
return strAsciiName;
}
extern "C" __declspec(dllexport) void FreeMemory(char* ptr)
{
if(ptr != NULL)
{
delete[] ptr;
ptr = NULL;
}
}