开发者

Wrapping a C++ object in extern "C"

开发者 https://www.devze.com 2023-03-08 15:56 出处:网络
consider a simple exa开发者_如何转开发mple class: class BankAccount { public: BankAccount() { balance =0.0; };

consider a simple exa开发者_如何转开发mple class:

class BankAccount {
public:
   BankAccount() { balance =0.0; };
  ~BankAccount() {};
   void deposit(double amount) {
      balance += amount;
   }
   private:
      double balance;
};

Now say I want to wrap this in extern "C" so that I can call it from many different programming languages such as C# and Java. I tried the following which seemed to work:

// cbankAccount.h:
extern "C" unsigned long createBackAccount(); 
extern "C" void deposit(unsigned long bankAccount, double amount);
// cbankAccount.cpp
unsigned long createBackAccount() {
  BankAccount *b = new BankAccount();
  return (unsigned long) b;
}
void deposit(unsigned long bankAccount, double amount) {
  BankAccount *b = (BankAccount*) bankAccount;
  b->deposit(amount);
} 

Is this portable? Is the type unsigned "unsigned long" large enough for an object pointer? Any other problems with this approach?

Thank in advance for any answers!


Yeah. It's bad. Really bad. unsigned long- just no. Return a properly typed BankAccount*- the other languages will see it on the other end as a generic pointer (such as System.IntPtr) and there's no need to return an untyped pointer when the binary interface doesn't type pointers anyway.

extern "C" BankAccount* CreateBankAccount() {
    return new BankAccount;
}
extern "C" void deposit(BankAccount* account, double amount) {
    account->deposit(amount);
}


That basically looks fine with one proviso. Trying to use an integer type to hold a pointer is not a great idea—much better to use void* since that, by definition, is the width of a pointer.


Actually, I think @DeadMG's answer is a cleaner approach than this.


Type-strong is even better than void *.

typedef struct BankAccountProxy *  BankAccountPtr;

BankAccountPtr createBackAccount() {
  BankAccount *b = new BankAccount();
  return (BankAccountPtr) b;
}


This is not portable, because unsigned long may be not long enough for a pointer. A not so rare platform where this happens is win64.

Better to use ptrdiff_t or void*.


It would probably be platform dependent whether long is large enough (probably not on x86-64) an alternative is to use something like swig


I'd use void* instead of unsigned long.

0

精彩评论

暂无评论...
验证码 换一张
取 消