Yan

Yan

  • NA
  • 3
  • 2.4k

call a C DLL from C#

Jul 16 2010 11:21 AM


Hi everyone,
i'm trying to call a DLL written in C from a program C# and got an error at the execution.
Here is the content of my C DLL :

/* file test.h */
#define DLL_EXPORT __declspec(dllexport)
DLL_EXPORT struct struct_test{
 int a;
 int b;
};
DLL_EXPORT int func_test(struct struct_test * t);
/*********************************************/
/* file test.c */
#include "test.h"
DLL_EXPORT int func_test(struct struct_test * t)
{
 return t->a+t->b;
}

 
and here is my C# code :
using System;
using System.Runtime.InteropServices;
public class csharp_test_class
{
 [StructLayout(LayoutKind.Sequential, Pack=1)]
 public struct struct_test{
  public int a;
  public int b;
 };
 [DllImport("test")]
 public extern static int func_test(
  ref struct_test t
 );
 public static void Main()
 {
  struct_test t = new struct_test();
  t.a = 3;
  t.b = 4;
  Console.WriteLine(func_test(ref t));
 }
}

The error recevied is :
PInvokeStackImbalance was detected :
A call to PInvoke function 'Project1!csharp_test_class::func_test' has unbalanced the stack. 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.
Does someone has an idea how to resolve that problem ?
Thanks in advance for your answers,
Best regards,
Yan302

Answers (2)