Interfacing with C++ Classes

BlitzMax Forums/BlitzMax Programming/Interfacing with C++ Classes

Let me share a subtly different approach that I find works better than the C style glue. It is a way you can still have the flavor of the C++ objects. And you can even use it to implement polymorphic behavior.

Here is simple slapped together C++ code. @Brucey ignore its just a single CPP file :)

fun.cpp
#include <iostream>
using namespace std; 
 
class IClassInterface {
public:
  virtual int Add(int x, int y) =0;
};


class ClassImplemenation : public IClassInterface {
 public:
	ClassImplemenation() {cout << "Creating Class\n"; }
	virtual ~ClassImplemenation() { cout << "Destroying\n"; }
	virtual int Add(int x, int y) { cout << "Adding "<<x<<"+"<<y<<"\n"; return x+y; }
};

extern "C" {
   IClassInterface* Create_IClassInterface()
   {
	return new ClassImplemenation(); 
   }	 
   
   void Free_IClassInterface(IClassInterface* instance)
   {
      delete static_cast<ClassImplemenation*>(instance);
   }
	
}


Now for the Max Code

test.bmx

SuperStrict

Import "fun.cpp"
Extern "C"
  Type IClassInterface 
  	Method Add:int(x:int,y:int)
  End Type
	
  function Create_IClassInterface:IClassInterface()
  function Free_IClassInterface(instance : IClassInterface)
End Extern



Print "Creating Class"
local class:IClassInterface = Create_IClassInterface()

Print "Testing Add"
Print "X+Y="+class.Add(2,3)
Free_IClassInterface(class)
class=NULL

Input "Press Enter to Quit"


Bascially the technique is how you implement interfaces with C++ by declaring a class "IClassInterface" abstract as all the methods are virtual pure. The key is you can not have any implemenations in these methods. That is for the implemenation class.

BlitzMax has supported virtual pure C++ classes since day one and can make wrapping a significantly cleaner than just everything as a Byte Ptr and make your code easier to manage.

Hope someone finds this useful.

DStastny