I am trying to wrap a sophisticated C/C++ API in Mathematica using WSTP, but can't work out how to return a pointer to a C/C++ data structure. This object was created on the C/C++ side of the wrapper, and I want to be able to pass it back to the API as a parameter later on.
I know how to wrap basic functions that return simple Mathematica objects like numbers and strings. In a perfect world, I would simply convert C++ objects into Mathematica expressions in my wrapper code. But this API's state cannot be represented as Mathematica expressions, so the objects need to remain on the C/C++ side. I need some way to wrap this state in a Mathematica expression. In other words, I would like to treat these structures as Abstract Data Types.
To make my question concrete, consider a silly example. Suppose I have an API written in C for controlling battle robots, and that I want to use Mathematica to guide a robot army to victory over the bad guys. Let's also assume that the RobotLink
structures are complicated and must remain in memory on the C side, and that there are multiple robots, so a singleton object won't do.
typedef struct { ... } RobotLink;
RobotLink *CreateRobotLink(int robotId);
void MarchTo(RobotLink *robot, char **targetLocation);
void ShootAt(RobotLink *robot, char **target);
void FreeRobotLink(RobotLink *robot);
How can I wrap this API to appear to Mathematica users as follows?
Needs["RobotCommsAPI`"]
robotLinks = createRobotLink /@ {1,2,3};
marchTo(#, "battle ground") & /@ robotLinks;
shootAt(#, "bad guys") & /@ robotLinks;
freeRobotLink /@ robotLinks;
Also, is there a way to have Mathematica call freeRobotLink
automatically, when the object is no longer needed?
Thanks very much in advance.
Comments
Post a Comment