简体   繁体   English

在C#中调用C DLL的问题

[英]Problem invoking C DLL in C#

I'm currently trying to invoke a method made in C from C# 我目前正在尝试从C#调用C语言中的方法

C code looks like this: C代码如下所示:

extern "C"  int addSum(int a, int b)
{
    return a*b;
}

extern "C" int getCount()
{
    return 12;
}

and C# code looks like this: 和C#代码看起来像这样:

 [DllImport("mydll.dll", SetLastError=true)]
 private static extern int addSum(IntPtr a, IntPtr b);
 [DllImport("mydll.dll", SetLastError = true)]
 private static extern int getCount();

 public static int mySum(int a, int b)
 {
     return suma(a, b);
 }

 public static int getMyCount()
 {
     return getCount();
 }

The code returns the right values but i'm getting the following error: 代码返回正确的值,但我收到以下错误:

addSum' has unbalanced the stack. addSum'使堆栈失衡。 This is likely because the managed PInvoke signature does not match the unmanaged target signature. 这很可能是因为托管PInvoke签名与非托管目标签名不匹配。 Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature. 检查PInvoke签名的调用约定和参数是否与目标非托管签名匹配。

Any sugestion regarding this issue ? 关于这个问题有什么消息吗?

Thanks 谢谢

You don't need to use IntPtr as argument. 您不需要使用IntPtr作为参数。 You could directly use integer values when defining the method signature: 在定义方法签名时,您可以直接使用整数值:

[DllImport("mydll.dll", SetLastError = true)]
public static extern int addSum(int a, int b);

[DllImport("mydll.dll", SetLastError = true)]
public static extern int getCount();

And then directly invoke the function: 然后直接调用函数:

int result = SomeClass.addSum(3, 4);
int count = SomeClass.getCount();

In addtion to the datatype which might or might not be a problem depending on the target platform, you might also need to look at the calling convention. 除了根据目标平台可能存在或可能不存在问题的数据类型之外,您可能还需要查看调用约定。 It is the calling convention that determines amoung other thing who is responsible for the the stack clean-up and the order that arguments are pushed on the stack or assigned to registers etc. 调用约定决定了负责堆栈清理的其他事情以及参数被压入堆栈或分配给寄存器等的顺序。

It is common for C code to use the cdecl calling convention. C代码通常使用cdecl调用约定。

[DllImport("mydll.dll", 
           SetLastError=true, 
           CallingConvention=CallingConvention.Cdecl)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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