0

It seems like a duplicate question from the title, but let me clarify that I have already searched and followed different methods.
Basically I have to import a managed C++ dll into a C# project. I consulted some tutorials and finally created a managed C++ dll. Now while importing the dll I got the following error:

An attempt was made to load a program with an incorrect format

I found some solutions like this but these solutions could not help me. Before facing this error I had to consult this solution and then this one too.

Here's a screenshot of how I am trying to import the dll:

Settings:

Importing the dll fine using build settings

Code:

Calling the dll in the code

Someone please guide me about the right way to import the dll in my project.

Community
  • 1
  • 1
Itban Saeed
  • 1,660
  • 5
  • 25
  • 38
  • Just FYI, "Managed C++" is only a thing prior to Visual Studio 2005. With VS2005, Microsoft introduced C++/CLI and the syntax is significantly different. – crashmstr Aug 06 '15 at 11:46
  • If you habe a C++CLI DLL, why don't you reference it directly? You would need that anyway for accessing the functions of that DLL. Your build event seems useless to me. – Tobias Knauss Aug 06 '15 at 11:50

2 Answers2

0

This C++ library is for certain architecture (x64 or x86). C# on the other hand is not(Any CPU), that is why this kind of error - C# most likely assumes You have a x64 unmanaged library. You should restrict the architecture in C# project to either of these (x64 or x86) so in both projects they are the same.

  • I have tried both of them but I am still facing the error – Itban Saeed Aug 06 '15 at 10:48
  • You have to be sure that both projects have the same architecture and that the function GetRegistryPath is properly exported from your unmanaged DLL! Because "Bad image" most likely means architectures do not match! – AccessViolation Aug 06 '15 at 10:54
  • One more thing - You should include file extension in DllImport attribute see https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.dllimportattribute(v=vs.90).aspx and as Niall said - if indeed the dll is managed You should add it to references of C# project. – AccessViolation Aug 06 '15 at 12:14
0

Should you not be copying the file as a pre-build step? Make sure it is in the correct location before the build. I would also remove the exit 0, it's not needed.

That DllImport is usual for native C-style APIs, not the managed and C++/CLI assemblies. These .Net assemblies, be they mixed mode or not, can be added in the usual assembly dependency locations.

If this is a "Managed C++" and not a "C++/CLI" assembly, it may also be incompatible with the target .Net framework.

Niall
  • 30,036
  • 10
  • 99
  • 142