gpt4 book ai didi

c++ - 使用非托管接口(interface)包装托管

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:52:00 26 4
gpt4 key购买 nike

我有一个公开一些接口(interface)的非托管库。用户可以实现接口(interface)并将它们与自定义实现一起粘贴到库中。

我想为这个库提供一个托管包装器。用托管接口(interface)包装非托管接口(interface)很容易。但就我而言,我想支持各种接口(interface)的用户实现,这意味着我需要采用接口(interface)的托管实现并使用其非托管对应项将其包装,然后再将其发送到库的非托管部分的深处。

我试过类似的方法:

class UnmanagedWrapper {
DoSomething() {m_clr.DoSomething();}
IManaged^ m_clr;
}

但我不能在非托管类中拥有托管成员,编译器正确地声明了这一点。

我可以在这里做些优雅的事情吗?

最佳答案

以下是一些相关信息,用于在一个库不受管理并且一种托管语言使用这些库时解决问题。

此信息的上下文是在 Visual Studio 中使用 GoogleTest 的一种方式:

Getting started with Google C++ Testing Framework

Important note for Visual C++ users If you put your tests into a library and your main() function is in a different library or in your .exe file, those tests will not run. The reason is a bug in Visual C++. When you define your tests, Google Test creates certain static objects to register them. These objects are not referenced from elsewhere but their constructors are still supposed to run. When Visual C++ linker sees that nothing in the library is referenced from other places it throws the library out. You have to reference your library with tests from your main program to keep the linker from discarding it. Here is how to do it. Somewhere in your library code declare a function:

__declspec (dllexport) int PullInMyLibrary() { return 0; }

If you put your tests in a static library (not DLL) then __declspec(dllexport) is

not required. Now, in your main program, write a code that invokes that function:

   int PullInMyLibrary(); 
static int dummy = PullInMyLibrary();

This will keep your tests referenced and will make them register themselves at startup.

In addition, if you define your tests in a static library, add /OPT:NOREF to your main program linker options. If you use MSVC++ IDE, go to your .exe project properties/Configuration Properties/Linker/Optimization and set References setting to Keep Unreferenced Data (/OPT:NOREF). This will keep Visual C++ linker from discarding individual symbols generated by your tests from the final executable.

There is one more pitfall, though. If you use Google Test as a static library (that's how it is defined in gtest.vcproj) your tests must also reside in a static library. If you have to have them in a DLL, you must change Google Test to build into a DLL as well. Otherwise your tests will not run correctly or will not run at all. The general conclusion here is: make your life easier - do not write your tests in libraries!

关于c++ - 使用非托管接口(interface)包装托管,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7379278/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com