为静态库设计托管 DLL (C++/CLI)

发布于 2024-12-11 12:36:53 字数 406 浏览 0 评论 0原文

我正在使用 C++/CLI 来实现 C 库。我在网上探索了一下。我有几个关于它的链接。

混合模式 C++/CLI 性能注意事项 - 最佳实践

开发一个 C++/CLI DLL,它将包装一个 C 静态库。

我真正想在这里讨论的一个建议是“不应在包装器中混合托管和非托管 C++ 代码”。我不明白它的含义。

当然,托管 DLL 将包含托管 C++ 代码和非托管 C++ 代码。

包装器的目的是将静态库的调用转换为托管代码 DLL。

请消除我的疑虑 - 我想对此发表评论。

I am working with C++/CLI for C Library. I explored in the net about it. I got several links about it.

Mixed mode C++/CLI performance considerations - best practices

I am developing a C++/CLI DLL which will wrap a C static library.

There was one suggestion that I really wanted to discuss here is "One should not mix up managed and unmanaged C++ code in wrapper". I don't understand meaning of it.

The managed DLL will, of course, contain managed C++ code and unmanaged C++ code.

The purpose of the wrapper is to translate calls from the static library to managed code DLL.

Please clear my doubts - I wanted comments on this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

辞旧 2024-12-18 12:36:53

如果您有常规 C++ 库(非 CLI),出于性能原因,您应该避免打开该库的“CLI”编译选项。

相反,创建一个只包含包装类的库是一种很好的做法。该库当然是 C++/CLI,并将创建一个可由常规 .Net 库引用的程序集。

因此,这可能就是建议所讨论的内容 - 为 CLI 包装器创建一个包装器库

- 更新问题的附录

托管 C++/CLI 类不应包含非托管代码,因为它/不能/包含许多类型的非托管代码。

例如,C++/CLI 类不能具有任何非引用或指针的非托管成员变量。这是因为 .Net 运行时垃圾收集器可能随时决定将对象放置在内存中的其他位置(这就是您需要固定内存等的原因)。如果 GC 决定将本机 C++ 对象移动到内存中的其他位置,则可能会使指向该对象的任何指针无效。这显然是不好的。

C++/CLI 是一种很棒的语言。但是,如果您使用它,您应该决定编写纯 .Net 代码,或者应该将其用作本机 C++ 和 .Net 之间的接口。在同一类中使用混合内存模型只会让事情变得混乱。

If you have a regular C++ library (non-CLI), you should avoid turning on the 'CLI' compilation option for that library, for performance reasons.

Instead it is good practice to create a library that just has your wrapper classes in it. This library will of course be C++/CLI, and will create an assembly that can be referenced by regular .Net libraries.

So that's probably what the advice would be talking about - create a wrapper library for your CLI wrappers

-- addendum for the updated question

A managed C++/CLI class should not contain unmanaged code because it /cannot/ contain many types of unmanaged code.

For example, a C++/CLI class cannot have any unmanaged member variables that are not references or pointers. This is because the .Net runtime garbage collector may decide to put the object somewhere else in memory at any time (this is the reason you need to pin memory etc.). If the GC decides to move your native C++ objects to some other place in memory, this will potentially invalidate any pointers you have to that object. This is obviously bad.

C++/CLI is a great language. If you use it, however, you should either decide to write pure .Net code, or you should use it as an interface between native C++ and .Net. Having mixed memory models in the same class just confuses things.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文