There are two projects (C# and Managed C++). C# projects needs to call a method in ManagedCPP project. in reference section of c# project the managed cpp dll is added.
if Line 1, 2 and 3 are uncommented and Line 4 is commented, then also following problem occurs:
Unhandled Exception: System.BadImageFormatException
The code base is as follows:
C# class:
using System.Runtime.InteropServices;
using ManagedCPP;
namespace CSharp
{
class Program
{
//[DllImport("ManagedCPP")] // Line 1
//public static extern void Convert(); // Line 2
static void Main(string[] args)
{
new Program().CreateObject();
}
private void CreateObject()
{
//Convert(); // Line 3
ManagedCPPEntryClass c = new ManagedCPPEntryClass(); // Line 4
Console.ReadKey();
}
}
}
C++/CLI class(.h):
namespace ManagedCPP
{
public ref class ManagedCPPEntryClass
{
public:
void Convert();
};
}
C++/CLI class(.cpp):
#include "ManagedCPP.h"
using namespace ManagedCPP;
void ManagedCPPEntryClass::Convert()
{
}
Make sure your native code (C++) is compiled with the same format (32 bits or 64 bits) as the .Net execution format of your C# application(32 bits or 64 bits again). This may be the cause of your problem.
By default .Net executes itself in the same format as the OS. You can force execution in a chosen format by setting a compilation option in visual studio.
I'm not an expert on the topic, but you should use DllImport to access a non-CLI assembly, while a CLI can be directly used in C# as if it were a native assembly (the advantage of using a common interface).
Commented lines are used to call unmamaged API Convert from unmanaged Dll IPF_ManagedCPP. Actually, IPF_ManagedCPP is managed Dll, and Convert is managed class method. Of course, this cannot work.
C++/CLI class library should be used by client .NET code exactly like any other class library. Unmanaged Dll can be used in .NET project by two ways: using PInvoke or using C++/CLI wrapper. You don't need PInvoke for IPF_ManagedCPP library.
精彩评论