How to compile C# application with C++ static library?
Asked Answered
S

5

27

I turned my C++ Dynamic link library into Static library just to acquire more knowledge. My question is how can I use the .obj file to compile both projects with C# express/MS visual studio?

Strawberry answered 8/4, 2009 at 11:22 Comment(0)
E
34

No, you can't access static libraries directly from C#. You have to use a DLL.

Extemporary answered 8/4, 2009 at 11:27 Comment(6)
I have to use a DLL,but Jon Skeet doesn't have to,he can compile anything. :) Thanks Jon.Strawberry
This must be possible with runtime linking to the static library and somehow interpret the static library's binary. I don't know C# but I'm pretty sure one can read binary files with it.Stranglehold
@Radek: And how do you propose to then run the code? There may be ways of doing it if you're willing to use various unmanaged functions, but at that point you're barely using C# any more.Extemporary
embedded virtual machine. Another way is to translate it into a DLL (probably with reassembling, relinking, whatever) just before using it, but then it's indeed not static anymore. It is difficult, but certainly possible.Stranglehold
@Radek: I think for most practical purposes, saying "you can't do it" is accurate. How far does it have to go before you'd accept "you can't do it" - if you had to build your own CLR with extra hooks, would that count?Extemporary
To update the outdated answer. If using IL2CPP Scripting backend rather than Mono, it's now possible to link against static libs because IL2CPP uses ahead of time compilation while Mono uses Just in time compilation.Quittance
C
20

The way to "use" a static library in C# is to first create a Managed C++ wrapper that will provide a facade for the rest of the managed world. As everyone else has already commented, C# only supports DLLs for P/Invoke.

Charleycharlie answered 8/4, 2009 at 12:8 Comment(1)
Conceptually this makes sense but assume the static libs were third party and compiled with /MTd, how do you cross into /MDd land required for /CLI?Langford
C
5

"Static library" means that the library is going to be merged with your final application. This concept doesn't exist in .net. .net supports DLLs only.

Commercialism answered 8/4, 2009 at 11:46 Comment(0)
Q
2

To update the outdated answer. If using IL2CPP Scripting backend rather than Mono, it's now possible to link against static libs because IL2CPP uses ahead of time compilation while Mono uses Just in time compilation.

Quittance answered 31/8, 2023 at 17:55 Comment(0)
R
1

No way to do that.

Only call DLL functions in runtime or create a COM object from your library

Reber answered 8/4, 2009 at 11:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.