简体   繁体   中英

Is it possible to use a C++ .lib file from within a C# program?

是否可以在C#程序中使用C ++ .lib文件?

There are plenty of ways. Read about "interop" in MSDN..

One way is to expose the lib as a DLL, and then use pinvoke to call these functions from a C# project. That limits you to a C-style interface, though.

If your interface is more complex (eg object oriented) you can create a C++/CLI layer that will expose the lib's class structure to your C# program. This means you'll have to create a managed C++ (or C++/CLI as it's now called) project; then design an interface in managed code that will be implemented by calls to native C++ (ie your lib).

Another way of doing this is by wrapping your lib with a COM interface. But COM's a pain, so I wouldn't...

Not directly. You can create a C++/CLI assembly that consumes the lib and then access that from C#, or you can wrap the lib as a DLL.

What you need is a managed wrapper (C++/CLI) around the native C/C++ library that you are working with.

If you are looking for any C++/CLI book I'd recommend Nishant Sivakumar's C++/CLI in Action

Already answered to wrap it but here's an example . Good luck!

I would take a look at swig , we use this to good effect on our project to expose our C++ API to other language platforms.

It's a well maintained project that effectively builds a thin wrapper around your C++ library that can allow languages such as C# to communicate directly with your native code - saving you the trouble of having to implement (and debug) glue code.

不可以。您只能使用C#程序中的完整.dll。

That depends, do you have any limitations on this scenario?

If you have a lib file, it should be possible to first compile it into a DLL file, secondly exposing the functions you want to call in the DLL interface, and thirdly, call them using C# native methods (have a look at pinvoke.net on how to do this bit).

you can't use a lib, but like the others said, you can use it if you wrap it into a dll.

swig can take the headers of your .lib, and if they are not too complex it can generate the dll for you which you would then call with a pinvoke from c# which would also be generated by swig.

if your library is complex and has reference counted smart pointers everywhere, you should find an alternative.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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