DllImport with CoreCLR (or in general: calling native code from CoreCLR)



Can someone tell me what are the plans regarding calling native code from code
running in the CoreCLR?

I try to port a C# project compiled against .NET2.0 to CoreCLR which uses lots of native
methods via DllImport (these are calling our C++ code and I have full control
also over this code base…). VS 2015 tells me that DllImport is not available
under “Core_mscorelibCoreClr.DNX Core 5.0” and by building it with “dnu build”
it also throws an error “The type or namespace name ‘DllImport’ could not be

I tried it with 1.0.0-beta4 shipped by VS2015 preview and with 1.0.0-beta5-12103.

Btw. I see lots of DllImports in the CoreCLR repo, and https://github.com/dotnet/corefx/issues/343
also states that DllImport works on CoreCLR.

So is DllImport supported? If yes, what is wrong with code like this:

 [DllImport("myLib.dll", CallingConvention = CallingConvention.StdCall)]
 internal static extern long NativeMethod();




how is the library called?


that’s just a string variable pointing to my own dll. I modified the code sample to make it simpler…

So the point is that I want to call my own compiled C++ library… But the compiler says that it does not know the DllImportAttribute for CoreCLR.


Use loadlibrary dllimport is slower but the main issue is you need to compile different C# versions for each runtime win 32 / win 64 / linux 32 etc. LoadLibrary can avoid that.

See http://stackoverflow.com/questions/27981719/c-sharp-native-interop-why-most-libraries-use-loadlibrary-and-delegates-instea


Yes, but what the stackoverflow answer says is this

“Yes, always favor [DllImport]. Having to use Marshal.GetFunctionPointerForDelegate() is a
very clumsy way and never necessary in practice. – Hans Passant Jan 16 at 11:46”

And what do you meand by “LoadLibrary”? Is it the LoadLibrary function from Kernel32.dll as described here http://blogs.msdn.com/b/jonathanswift/archive/2006/10/03/dynamically-calling-an-unmanaged-dll-from-.net-2800_c_23002900.aspx ? It still won’t work, because the LoadLibrary function is used via DllImport and it does not compile for CoreCLR. The only solution which could maaybe work is this C++/CLI wrapper from the referenced blogpost, but I think that is really not something which scales…

So the question is still this: How is managed/unmanaged interop working in CoreCLR, and is DllImport supported? If someone could point me to a tutorial or a blogpost I would be very happy.



Are you referencing System.Runtime.InteropServices in your project.json?



Yes, that solved it! Many thanks. (It was actually referenced, but not the correct version…)

So I guess the answer for the original question is yes… DllImport is indeed supported…



Great. This is a problem with the experience today. I got bit with the Path class recently in the same way. It is something that we need to solve. Thanks for playing along.

.NET Foundation Website | Blog | Projects | Code of Conduct