Using a C ++ DLL in a C # Project

I got a C ++ dll that should be integrated into a C # project.

I think I found the right way to do this, but the dll call gives me this error: System.BadImageFormatException: An attempt was made to load a program with the wrong 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 use 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 do this?

Thanks a lot Frank

+5
source share
4 answers

try using __stdcall(or WINAPIor APIENTRY) in a function exported from a DLL.

+4
source

# AnyCPU x86 ( "" ).

+4

PASCAL, Windows stdcall. .Net , # :

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

:

1- dll ++

**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.

Cpp

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

first_dll.dll

2- #

#

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

#

Using first_dll; 

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

.dll ++, VS2010, #, VS2013. .

0

All Articles