Using C++ DLL in C# project

2020-03-19 03:47发布

问题:

I got a C++ dll which has to be integrated in a C# project.

I think I found the correct way to do it, but calling the dll gives me this error: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

This is the function in the dll:

extern long FAR PASCAL convert (LPSTR filename);

And this is the code I'm using in C#

namespace Test{
public partial class Form1 : Form
{
    [DllImport("convert.dll", SetLastError = true)]
    static extern Int32 convert([MarshalAs(UnmanagedType.LPStr)] string filename);

    private void button1_Click(object sender, EventArgs e)
    {
        // generate textfile
        string filename = "testfile.txt";

        StreamWriter sw = new StreamWriter(filename);
        sw.WriteLine("line1");
        sw.WriteLine("line2");
        sw.Close();

        // add checksum
        Int32 ret = 0;
        try
        {
            ret = convert(filename);

            Console.WriteLine("Result of DLL:  {0}", ret.ToString());
        }
        catch (Exception ex)
        {
            lbl.Text = ex.ToString();
        }
    }
}}

Any ideas on how to proceed with this?

Thanks a lot, Frank

回答1:

try to use __stdcall (or WINAPI or APIENTRY) in the function exported from the DLL.



回答2:

Try to switch your C# code from AnyCPU to x86 (in Properties dialog).



回答3:

Your exported function uses the PASCAL calling convention, which in Windows is the same as stdcall. The .Net runtime needs to know about that, so modify your C# method signature as follows:

[DllImport("convert.dll", SetLastError = true, CallingConvention=CallingConvention.StdCall)]
static extern Int32 convert([MarshalAs(UnmanagedType.LPStr)] string filename);


回答4:

Two main steps involved are

1- Creating a C++ dll

In visual studio

**New->Project->Class Library** in c++ template Name of project here is first_dll in visual studio 2010. Now **declare your function as public** in first_dll.h file and write the code in first_dll.cpp file as shown below.

Header File

Cpp File

Check **Project-> Properties -> Configuration/General -> Configuration Type** 
this option should be **Dynamic Library(.dll)** and build the solution/project now.

first_dll.dll file is created in Debug folder

2- Linking it in C# project

Open C# project

Rightclick on project name in solution explorer -> Add -> References -> Browse to path
where first_dll.dll is created and add the file 

Add this line at top in C# project

Using first_dll; 

Now file can be accessed using below statement in some function

double var = Class1.sum(4,5);

I linked the C++ project .dll created in VS2010 to C# project created in VS2013. It works well.