3

I am in the process of creating a CLI project to wrap around an existing native c++ project (two separate projects in the same solution file). I'd like to include a pointer to a native class as a member in a managed class. From the documentation that I've read online, this can be done if both the managed and unmanaged code are together in the same project. If the native and managed code are in separate projects, then the only option is to use dllimport and dllexport attributes between the two projects, and to export the native code class functions as static functions.

Are these my only options, or can I import and export an entire native class between two separate projects? I'm asking because this determines how I design my managed wrapper. Thanks in advance.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
John
  • 1,167
  • 1
  • 16
  • 33

1 Answers1

5

Well the word "pointer" threw me for a minute. You mean you want to use some native code from your C++/CLI code without P/Invoke? Sure. Just include-the-header, link-to-the-lib. Exactly what you'd do if they were both native. These days it's called C++ Interop - I like the old name (It Just Works Interop) better.

You can of course include a header from anywhere, and add a linker input from anywhere, so they technically don't have to be in the same .sln, but Visual Studio will make your life a little easier if they are.

Kate Gregory
  • 18,808
  • 8
  • 56
  • 85
  • 2
    It also helps if the native project is set to build a static .lib instead of a DLL. Otherwise you can easily run into problems like allocating from one CRT heap and trying to free with another. And sometimes it's worth activating the "Link library sources" option, since linking to a static library won't run global constructors in objects that aren't otherwise needed. "It Just Works (if you're careful", but is much much much easier than p/invoke. – Ben Voigt Mar 28 '11 at 23:08
  • That's good to know. My native code is a dll and not static lib. – John Mar 29 '11 at 14:05
  • You can get VS to make you a "convenience lib" that you can link to from the calling project. – Kate Gregory Mar 29 '11 at 14:06
  • Do you have a link on how to make a convenience lib? – John Mar 29 '11 at 14:16
  • Apparently this century they're called "import libraries" - see http://stackoverflow.com/questions/584041/how-do-i-build-an-import-library-lib-and-a-dll-in-visual-c – Kate Gregory Mar 29 '11 at 14:28