我必须使用提供一些回调程序的delphi dll。如果我将它们与C#结合使用,一切正常。如果我使用C ++,则回调不起作用。在delphi dll中,回调的编写方式如下:
procedure addConnectionCallBack(connectCallback: TConnectCallback); StdCall;
begin
initMyConnection();
if assigned(MyConnection) then
begin
MyConnection.addConnectionCallBack(connectCallback);
end;
end;
使用C#时一切正常:
// make delegate
public delegate void ConnectionCallBack();
// define dll
[DllImport(_dll_name, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
public static extern void addConnectionCallBack(ConnectionCallBack ccb);
// function with signature of ConnectionCallBack
private void showConnected() {
Console.WriteLine("connected");
}
// address callback to dll
public void start() {
addConnectionCallBack(showConnected);
}
在C ++中,我无法解决它:
typedef void (__stdcall *ConnectionCallBack)();
typedef void (__stdcall *addConnectionCallBack)(ConnectionCallBack);
addConnectionCallBack _addConnectionCallBack;
// !!! this should be called from delphi dll, but isn't !!!
void __stdcall showConnected() {
std::cout << "connected" << std::endl;
}
//auto showConnected = []()->void {std::cout << "connected" << std::endl; };
int main()
{
LPCWSTR _dll_name = L"MyDelphi.dll";
HINSTANCE _hModule = NULL;
_hModule = LoadLibrary( _dll_name);
assert(_hModule != NULL);
_addConnectionCallBack = (addConnectionCallBack) GetProcAddress(_hModule, "addConnectionCallBack");
ConnectionCallBack conn = showConnected;
_addConnectionCallBack(conn);
// do some other dll calls which work and force the callback.
FreeLibrary(_hModule);
return 0;
}
其他对dll的返回字符串的调用正在工作。尝试以各种方式使用功能指针或std::function
/std::bind
没有运气。
请有人可以检查我的C ++代码并给我提示!我再也没有想法了。
我通过使用Visual Studion Win32 Project模板或将C ++主要功能修改为以下方式解决了该问题:
int CALLBACK WinMain( In HINSTANCE hInstance, In HINSTANCE hPrevInstance, In LPSTR lpCmdLine, In int nCmdShow) {}
这样可以使dll的进程保持活动状态。
感谢您的所有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句