开发者

writing unmanaged DLL consumable by C#/.NET code

I need to implement a small part of my application logic in native code. To test PInvoke capabilities I created a simple solution with an unmanaged C++ Win32 Dll and a WPF project that consumes the dll functions using PInvoke. The problem I run into is that i receive exception about "unbalancing the stack" and "possible signature mismatch"

Here is my code:

1) C++ (d开发者_C百科ll)

#include <stdio.h>
#include <Windows.h>

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

2) C#:

public partial class MainWindow : Window

{
    [DllImport("MyLibrary.dll")]
    static extern int add(int a, int b);
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnVersion_Click(object sender, RoutedEventArgs e)
        {

            var res = add(3,2);
        }
    }

The code throws an exception stating "This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature."

Where is my mistake?


solved :) it seems i forgot __stdcall keyword in c++ function definition It should have been: __declspec(dllexport) int __stdcall add(int a, int b)


Try this signature for the unmanaged function:

extern "C" __declspec(dllexport) int add(int a, int b)

THe issue was to do with C++ name mangling. Without extern "C" the name gets mangled and the C# DLL cannot find it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜