简体   繁体   English

在由PInvoke返回给C函数的实例化C ++类上调用函数

[英]Call functions on an instantiated C++ class returned by a PInvoke to a C function

I have an unmanaged DLL that exports C style non-member functions for creating (say CreateObject) and destroying objects (DestroyObject). 我有一个非托管DLL,可导出C样式的非成员函数来创建(例如CreateObject)和销毁对象(DestroyObject)。 CreateObject returns a C++ class as a void*, which in the unmanaged code is cast to a known interface (defined only in a header file) and worked with. CreateObject将C ++类作为void *返回,该类在非托管代码中强制转换为已知接口(仅在头文件中定义)并使用。 Is there a way to call methods on the IntPtr that is returned to me by CreateObject? 有没有一种方法可以调用由CreateObject返回给我的IntPtr上的方法?

Dumpbin /EXPORT doesn't show me any methods of the C++ class, just the exported C functions (mentioned above). Dumpbin / EXPORT没有显示任何C ++类的方法,仅显示了导出的C函数(如上所述)。

I would like to avoid having to write C++ CLI code or a purely unmanaged DLL that simply exposes methods on this class as function wrappers if possible 我想避免不得不编写C ++ CLI代码或纯粹的非托管DLL,如果可能的话,该DLL仅将此类上的方法公开为函数包装器

This is Windows/MSVC only, so answers that restrict compatibility to Windows/MSVC are fine. 这仅是Windows / MSVC,因此将兼容性限制为Windows / MSVC的答案很好。

NOTE: I'm talking about invoking C++ methods on a void*/IntPtr returned by a C function - not P/Invoking the C functions. 注意:我说的是在C函数返回的void * / IntPtr上调用C ++方法,而不是在P /调用C函数上。

Thanks! 谢谢!

If you are ruling out C++/CLI, and only have an IntPtr containing the address of the instance then you have few options remaining. 如果您不使用C ++ / CLI,并且只有一个包含实例地址的IntPtr ,那么您几乎没有其他选择。

As I see it you are left with p/invoke. 如我所见,您留下了p / invoke。 In order to call a method you'll need to export it from your unmanaged code. 为了调用方法,您需要将其从非托管代码中导出。 You'll also need to be careful about the calling convention. 您还需要注意调用约定。 Commonly it will be __thiscall . 通常是__thiscall When you write the p/invoke, you must explicitly add the this pointer as the first parameter. 编写p / invoke时,必须显式添加this指针作为第一个参数。

This is fine so far as it goes. 就目前而言,这很好。 But you'll not be able to export virtual methods this way. 但是您将无法以这种方式导出虚拟方法。 You cannot call them using p/invoke. 您无法使用p /调用来呼叫他们。

Frankly though the cleanest and simplest way to do this interop is with our old friend, tried and tested COM. 坦白地说,尽管最干净,最简单的方法是与我们的老朋友经过反复测试的COM进行交互。 This very scenario is just what it was designed for. 这种情况正是它的设计目的。 C++ classes are not designed for interop across compiler/language boundaries. C ++类不适用于跨编译器/语言边界进行互操作。 That's what COM is for. 那就是COM的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM