26

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?

Ivan Prodanov
  • 34,634
  • 78
  • 176
  • 248

5 Answers5

31

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 3
    I have to use a DLL,but Jon Skeet doesn't have to,he can compile anything. :) Thanks Jon. – Ivan Prodanov Apr 08 '09 at 11:32
  • 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. –  Mar 23 '11 at 15:34
  • @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. – Jon Skeet Mar 23 '11 at 15:52
  • 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. –  Mar 23 '11 at 15:56
  • 2
    @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? – Jon Skeet Mar 23 '11 at 16:02
  • 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. – Justin Aug 31 '23 at 17:56
19

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.

Erich Mirabal
  • 9,860
  • 3
  • 34
  • 39
  • 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? – Ternary Jan 06 '14 at 00:23
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.

Mohammad Tayseer
  • 509
  • 1
  • 5
  • 10
1

No way to do that.

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

abatishchev
  • 98,240
  • 88
  • 296
  • 433
0

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.

Justin
  • 447
  • 4
  • 10
  • 33