07-26-2023, 03:54 PM
consider a simple example 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!
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!