CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jul 2010

    Question calling a C DLL from C#

    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;
     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,


  2. #2
    Join Date
    May 2007

    Re: calling a C DLL from C#


    The default calling convention is 'WinApi' which results in StdCall on windows which is incorrect for you as you explicitly choose cdecl in your program. Just set it to Cdecl and you're done.
    www.monotorrent.com For all your .NET bittorrent needs

    NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.

  3. #3
    Join Date
    Jul 2010

    Re: calling a C DLL from C#


    Thanks, it solves my problem.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.