LabDog
LabDog

Reputation: 15

C++/CLI managed wrapper around C static library

Help!

I'm totally exhausted/frustrated with what seems to be a reasonably easy task. I’m not sure what I'm doing wrong; let alone if I'm doing it correct. I'm "required" to use an existing library (a C static library – over 100,000 lines of straight C code) in developing a WPF application (VS 2010, C# 4.0). Oh, and I can't touch the existing C code - use it as is!

I've read so many postings (advanced topics, how-to, etc), yet I'm so new to C++/CLI that it's just not making sense. From what I've read the best approach is to wrap the C static library as follows:

Unmanaged C static library <---> C++/CLI managed wrapper DLL <---> managed WPF application

This is the stripped down C header file:

/* Call this function to execute a command. */
int issue_command(int command, long param1, long param2);

/* Completion call back function; you must supply a definition. */
extern  int command_completed(int command, long param1, long param2);

struct struct_command_str
{
      char   command_str[10];
      char   param1_st[2];
      char   param2_st[2];
      char   success;
};

/* You must supply definitions to the following extern items. */
extern  int command_status;
extern struct struct_command_str  command_str;

The problem(s):

What I can’t seem to do correctly is provide a C++/CLI implementation for the call back functions, and the two extern items (command_status and struct command_str).

Can someone provide a sample C++/CLI implementation for the above missing call back functions and externs?

Thanks in advance for your assistance.

Upvotes: 1

Views: 1790

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283624

when you implement these in your c++/cli module, use the same signature shown in the c header file,but prefixed with extern "C".

also put an extern "C" block around the #include of the C header file.

Upvotes: 1

rlods
rlods

Reputation: 465

in your C++/CLI managed wrapper project, add 2 files :

a .c file :

extern void doSomething();

int command_status = 0;

struct_command_str command_str = { "command1", "p1", "p2", 't' };

int command_completed(int command, long param1, long param2) {
    ...
    command_status = 1;
    ...
    doSomething();
    ...
    command_status = 2;
    ...
    return 3;
}

a cpp file

void doSomethingManagedWrapper() {
    ...
    call managed code
    ...
}

void doSomething() {
    doSomethingManagedWrapper();
}

Upvotes: 3

Related Questions