调用从C++代码导出在DLL中的Delphi CLASS
Call Delphi CLASS exported in DLL from C++ code
我在C++代码中使用Delphi class时遇到问题。 德尔福 DLL 演示,用于导出返回对象的函数。我的德尔福Dll代码如下:
library DelphiTest;
// uses part....
type
IMyObject = interface
procedure DoThis( n: Integer );
function DoThat : PWideChar;
end;
TMyObject = class(TInterfacedObject,IMyObject)
procedure DoThis( n: Integer );
function DoThat: PChar;
end;
// TMyObject implementation go here ...
procedure TMyObject.DoThis( n: Integer );
begin
showmessage('you are calling the DoThis methode with '+intToStr(n) +'parameter');
end;
function TMyObject.DoThat: PChar;
begin
showmessage('you are calling the DoThat function');
Result := Pchar('Hello im Dothat');
end;
导出 DLL 函数:
function CreateMyObject : IMyObject; stdcall;export;
var
txt : TextFile;
begin
AssignFile(txt,'C:log.log');
Reset(txt);
Writeln(txt,'hello');
Result := TMyObject.Create;
end;
exports CreateMyObject;
在我的C++项目中,我声明了IMyObject接口如下:
class IMyObject
{
public:
IMyObject();
virtual ~IMyObject();
virtual void DoThis(int n) = 0;
virtual char* DoThat() = 0;
};
我的主要功能如下:
typedef IMyObject* (__stdcall *CreateFn)();
int main()
{
HMODULE hLib;
hLib = LoadLibrary(L"DelphiTest.dll");
assert(hLib != NULL); // pass !!
CreateFn pfnCreate;
pfnCreate = (CreateFn)GetProcAddress((HINSTANCE)hLib, "CreateMyObject");
if (pfnCreate == NULL)
{
DWORD errc = GetLastError();
printf("%un", errc); // it gets error 127
}
else{
printf("success loadn");
}
IMyObject* objptr = pfnCreate();
objptr->DoThis(5);
FreeLibrary(hLib);
int in;
scanf_s("%i", &in);
return 0;
}
在这个例子中,当我尝试访问导出的函数时,我在运行时遇到错误。 错误在行: IMyObject* objptr = pfnCreate();
你能告诉我我的例子有什么问题吗?如果可能的话,从C++代码访问Delphi类(在DLL中)的任何工作示例。
第一个问题是调用方法的约定。Delphi 接口使用 register
,这是 Delphi 特定的调用约定。使用 stdcall
,例如,接口的方法。
下一个问题是在C++。您的C++接口必须派生自IUnknown
。此外,它不应声明构造函数或析构函数。
除此之外,您的德尔福代码导出PWideChar
不会映射到char*
。它映射到wchar_t*
.
展望未来,返回PChar
在这里工作正常,因为您的实现返回文本。但是更严肃的代码可能希望使用动态分配的字符串,此时您的设计是有缺陷的。
请注意,您需要成为提升管理员才能在系统驱动器的根目录下创建文件。所以这是另一个潜在的失败点。
我预计还有其他错误,但这就是我到目前为止发现的全部。
相关文章:
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 为什么导入Mixed native/CLR lib.dll的本机C++应用程序没有在Mixed lib.dll中的外部变
- 如何在窗口中使用注入的 dll 中的参数调用函数
- .EXE是否可以使用间接导入的 DLL 中的符号?
- VB.NET DLL中的C++DLL函数复制
- 如果使用低于 VS2015 的 vc++ 编译器版本编译,则 DLL 中的访问冲突
- 不能使用隐式链接.dll中的类
- C DLL中的Python对象
- 包括DLL中的OpenVDB;将错误与Visual Studio 2015联系起来
- 为什么 Python 需要 DLL 中的 GetMessage 消息泵送,而不是 Qt
- 本机 dll 中的动态内存分配
- 使用 c++ DLL 中的函数
- 放置在外部 DLL 中的类中的字符串数据的内存损坏
- 如何在C++中修复PyImport_Import(python35.dll中的异常)
- dll中的vector.h在我的应用中不可用
- 从Qt(c ++)调用DLL中的函数
- LNK2019某些类函数,但不在其他类函数(DLL 中的模板类)上
- 如果在调用 DLL 中的函数时没有传递足够的参数,会发生什么情况?
- Visual Class 在 DLL 中的成员函数中返回自身C++
- 无法追加到 COM Dll 中的字符串 奇怪的行为