I´m trying to call a method that is in a C++ dll declarated as __declspec(dllexport) to use in C#, but I don´t know how to return a string value from C++ and how to declare the signature using DllImport in C#.
C++ code "VNVAPI.dll"
__declspec(dllexport) char * GetGpuName(int phyGPUid)
{
CNvidia * pInstance = CNvidia::GetInstance();
char szName[512]={0};
pInstance->GetGpuName(phyGPUid,szName,512);
return szName;
}
C# method signature:
[DllImport("VNVAPI.dll")]
public static extern char GetGpuName(int phyGPUid);
Error generated:
A call to PInvoke function 'Core!Core.Hardware.IO.NVAPI::GetGpuName' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.
Thanks.
static
scenario here. I still had @David Heffernan 's answer in my head. Is there any difference between the way memory is allocated forstatic
between C and C++? – leppiestatic
isn't a fix, the pinvoke marshaller is going to try to release the string with CoTaskMemFree. That goes kaboom on Vista and Win7. The real fix is to pass the buffer + length as an arguments, StringBuilder on the managed side. – Hans Passant