Is there a simple way to work with C++ objects directly from C? I want to expose some classes from C++ to C or to FFI(foreign function interface). Sure, I can write a stuff like that:
class Foo{
....
};
void *make_foo(...){
Foo *ptr = new Foo(..)
return static_cast<void *>(ptr);
}
..
int *foo_method1(void *fooptr, ...){
Foo *ptr = static_cast<Foo*>(fooptr);
}
But there is a simpler method?
Object-Oriented Programming in C Although the fundamental OOP concepts have been traditionally associated with object-oriented languages, such as Smalltalk, C++, or Java, you can implement them in almost any programming language including portable, standard-compliant C (ISO-C90 Standard).
In terms of C programming, an object is implemented as a set of data members packed in a struct , and a set of related operations. With multiple instances, the data for an object are replicated for each occurrence of the object.
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc. In other words, object is an entity that has state and behavior. Here, state means data and behavior means functionality. Object is a runtime entity, it is created at runtime.
Create an Object In C++, an object is created from a class. We have already created the class named MyClass , so now we can use this to create objects. To create an object of MyClass , specify the class name, followed by the object name.
That, in general, is the simplest method.
Remember, too, that you'll need to use extern "C"
on all of your C "wrapper" methods, as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With