简体   繁体   中英

Loading unmanaged DLLs in WPF applications

I know that my question may seem duplicated. But believe me, I have tried several answers proposed on this site and had no luck by far. So I would be very grateful if anyone could please tell me what is wrong with what I am doing. A clear and step-by-step guide would be much appreciated by me and hopefully other ones who are beginners in dealing with DLLs and WPF (I have already tried this and this and this ).

Here is a C++ code in its simplest form:

#include <stdio.h>
#pragma unmanaged

extern "C"  
{
    __declspec(dllexport) int add(int a,int b) 
    {
        return a+b;
    }
    __declspec(dllexport) int subtract(int a,int b) 
    {
        return a-b;
    }
}

OK, so I put this in a DLL project in Visual C++ 2013 and build it. Which is successful and gives me a file named OurDLL.dll .

Now, I create a new C# WPF application, write the simplest methods possible and add the following lines to the file MainWindow.xaml.cs :

/// some using statements

using System.Runtime.InteropServices; 
namespace test1
{
    public partial class MainWindow : Window
    {
        [DllImport("OurDll.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int add(int a, int b);

        /// the rest of the code

The code compiles and builds successfully. I have put the DLL file into the folder test1\\bin\\Debug . But whenever I try to use the add function, an exception window appears telling this:

An unhandled exception of type 'System.BadImageFormatException' occurred in test1.exe

Additional information: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

Now I am really frustrated and have no idea what to do :(

Most likely the problem is the discrepancy of the build settings for your C++ and C# apps.

Try to check this , this and this answers. Hope that will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM