我想从 C 程序中调用这个 C++ 函数。我想使用 char* errorMessage 返回错误消息。当我在代码中执行 return errorMessage 时,返回后我在 C 应用程序中得到了 char 指针。但是如果我尝试 errorMessage = SafeStringHeap(string("File name was empty."));
我总是在我的 C 应用程序中得到一个空指针。
我尝试在 C 应用程序中使用以下文本调用我的函数:
char* errorMessage = NULL;
TAFMessage = (*TAFParseMessageFile)(NULL, errorMessage);
功能:
static char* SafeStringHeap(string message)
{
//Save string on the heap
char * cstr = new char[message.length() + 1];
strcpy_s(cstr, message.length() + 1, message.c_str());
return cstr;
}
extern "C" __declspec(dllexport) const char* TAFParseMessageFile(const char* fileName, char* errorMessage)
{
if (fileName == NULL)
{
errorMessage = SafeStringHeap(string("File name was empty."));
return errorMessage;
}
return NULL; // TODO: set errorMessage
}
最佳答案
受制于上述提出的其他问题。尝试将您的 errorMessage 参数更改为 char **(指向 char 指针的指针),然后执行:
*errorMessage = SafeStringHeap(...)
并且在调用函数时传递&errorMessage
关于C++ DLL 字符参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26388220/