1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Making a C function pointer work with C-style stack based calling mechanics in C++

Discussion in 'C++' started by mani8899, May 24, 2011.

  1. mani8899

    mani8899 New Member

    Joined:
    May 24, 2011
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    I want to call a pure C style function from a dll in my C++ program. I tried casting my function pointer using reinterpret_cast to __cdecl and still the calling convention of _stdcall seems to be preserved. I am new to Windows C++ programming.

    This is my C++ call
    Code:
    reinterpret_cast< Error ( __cdecl*)(int,int)> (GetProcAddress(Mydll::GetInstance()->ReturnDLLInstance(), "add"))(1,10)
    actual function in the dll is

    Code:
    Error __cdecl add(int,int);
    Debugger throws me the error run time check failure #0. I am working in Windows-C++. Also I am exporting functions from my dll and I dont have access to my C files.
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    Re: Making a C function pointer work with C-style stack based calling mechanics in C+

    Usually to call C from C++ you just need to extern "C" the prototype:
    Code:
    extern "C"
    {
    Error add(int,int);
    }
    
    Then the compiler knows not to mangle the name and not to look for a mangled name.
     
  3. mani8899

    mani8899 New Member

    Joined:
    May 24, 2011
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Re: Making a C function pointer work with C-style stack based calling mechanics in C+

    Thanks! But what if I cannot work with the C code.I just have it as a dll. In that case is there a work around??
     
  4. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    Re: Making a C function pointer work with C-style stack based calling mechanics in C+

    extern "C" is C++ code, not C code. This is what you put in the C++ code to make it call the function in the DLL. You still need a prototype, and you extern "C" it to stop the compiler mangling the names, then the linker resolves the call.
     

Share This Page