Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C++ DLL in C# project

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

like image 611
Frank Avatar asked Jun 08 '10 07:06

Frank


People also ask

What is DLL in C?

In Windows, a dynamic-link library (DLL) is a kind of executable file that acts as a shared library of functions and resources. Dynamic linking is an operating system capability. It enables an executable to call functions or use resources stored in a separate file.

Can I use a C++ DLL in C #?

Yes, it will work.

How do I use a DLL file?

Open the folder with the DLL file. Once you find the folder, hold the Shift key and right-click the folder to open the command prompt directly in that folder. Type "regsvr32 [DLL name]. dll" and press Enter.


1 Answers

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

like image 118
Oleg Avatar answered Oct 24 '22 10:10

Oleg