将C ++ .lib和.h文件导入C#项目? [英] Import a C++ .lib and .h file into a C# project?

查看:739
本文介绍了将C ++ .lib和.h文件导入C#项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始一个C#项目,并希望导入一个C ++ .lib和它的相应的头文件(.h)文件。

I have just started a C# project and want to import a C++ .lib and it's corresponding header (.h) file.

我阅读过各种提及.dll而不是.lib的帖子,这让我很困惑。

I've read various posts that all mention .dll, rather than .lib, which is confusing me.

下面的图片显示了我指的.lib和.h文件,我所做的就是将它们拖到项目中。

The image below shows the .lib and .h file I'm referring to, all I've done is drag them into the project.

任何人都可以点我更清楚地说明如何去做这件事?我相信它不可能像看起来那么难。

Can anyone point me to a clearer explanation of how to go about doing this? I'm sure it can't be as hard as it seems.

推荐答案

你可以做什么,是创建一个C ++ / CLI包装,包装器。创建的包装dll你可以很容易地在你的C#项目中引用。这当然需要一些工作来创建托管/非托管包装器,但是从长远来看会有回报。

What you could do, is creating a C++/CLI wrapper and expose the functionality of the lib you want to use via your wrapper. The created wrapper dll you can easily reference in your C# project. This of course takes a little bit of work to create the managed/unmanaged wrapper, but will pay off in the long run.

要创建托管C ++项目选择C ++项目模板CLR和类库。在这里你可以链接到你的lib,使用头文件按照你惯用的方式。

To create a managed C++ project select under the C++ project templates CLR and Class Library. Here you can link to your lib, use the header file the way you are used to.

接下来创建一个新类(ref类)并包装你的库。示例可能如下所示:

Next create a new class (ref class) and wrap your library in it. An example might look something like this:

LibHeader.h

int foo(...);

你这样写一个包装类:
Header:

You write a wrapper class like this: Header:

Wrapper.h

public ref class MyWrapper
{
    public:
        int fooWrapped();
};

您的实现:

Wrapper.cpp

#include Libheader.h

int MyWrapper::fooWrapped()
{
     return foo();
}

为简单起见,命名空间和所有的好东西都省略了。
现在,您可以在C#代码中使用MyWrapper,就像任何其他托管类一样简单。当然,当lib的接口变得更复杂,你必须考虑一点,但它可能有助于从应用程序中分离lib代码。希望有一些光。

Namespaces and all the good stuff omitted for simplicity. Now you can use MyWrapper in your C# code just as easy as any other managed class. Of course when the interface of the lib gets more complicated you have to think about it a bit more, but it might help to separate the lib-code from your application. Hope to have shed some light on it.

这篇关于将C ++ .lib和.h文件导入C#项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆