5

The function in dll has the prototype below

void Foo(int arg1, int& arg2); 

The question is, how to declare the function prototype in C?

Is the declaration legal?

void Foo(int, int*); 
6
  • Since the dll is made by 3rd party, I am afraid the function in dll can't be changed. Commented Aug 30, 2017 at 6:34
  • 1
    Then you need to write an "adapter DLL" or you have to embed this adapter in your program using this DLL. Commented Aug 30, 2017 at 6:35
  • Your code may be in C, but the question really is more about C++, I think Commented Aug 30, 2017 at 6:36
  • 2
    @StoryTeller it's about interfacing both, one of the rare cases both tags are appropriate ... Commented Aug 30, 2017 at 6:36
  • Thanks to both of you. :) Commented Aug 30, 2017 at 6:45

2 Answers 2

8

Is the declaration legal?

It is, but it doesn't declare the same function. If you need a C API, you cannot use a reference. Stick to a pointer, and make sure the function has C linkage:

extern "C" void Foo(int, int*) { // Function body } 

If you cannot modify the DLL code, you need to write a C++ wrapper for it that exposes a proper C API.

Sign up to request clarification or add additional context in comments.

Comments

5

You need an adapter, consisting of a C++ translation unit and a header usable from both C and C++, like this (use better names of course):

adapter.h:

#ifndef ADAPTER_H #define ADAPTER_H #endif #ifdef __cplusplus extern "C" { #endif void adapter_Foo(int arg1, int *arg2); // more wrapped functions #ifdef __cplusplus } #endif #endif 

adapter.cpp:

#include "adapter.h" // includes for your C++ library here void adapter_Foo(int arg1, int *arg2) { // call your C++ function, e.g. Foo(arg1, *arg2); } 

You can compile this adapter into a separate DLL or you can have it as a part of your main program. In your C code, just #include "adapter.h" and call adapter_Foo() instead of Foo().

5 Comments

Wouldn't it be closer if the C++ reference was represented as a const pointer in C?
@cdarke I don't think this matters much. making the pointer (as opposed to the data it points to) const only affects the code inside the function, and it's just a wrapper anyways...
@cdarke - const when applied to arguments in function declarations is ignored (you get the same declaration as if there was no const). At the definition, you can add it if you want the compiler to catch modifications. But like Felix said, I too think it's moot here.
Why not make the definition as accurate as possible?
@alk a const like in int *const arg2 has no effect at all on the caller, so why bother? It's just unnecessary clutter.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.