Tuesday, March 29, 2016

Calling C++ from C

<< Prev: Structs and Pointers       Next: Workqueues >>

It turns out I made a little mistake there at the end of the Wait Queues post.

It's not actually a total disaster if C code (ported from Linux) needs to call C++ code (in the OS X driver).

This one I stumbled across completely by accident, by reading someone else's code that does something unrelated.

The magic is in OSMetaClassBase::OSMemberFunctionCast. This feature of a C++ class converts a pointer to one of its member functions (including a reference to the specific instance it operates on) to a C function pointer.

So it goes like this:
  1. The C code declares a function pointer type as a typedef (specifying the number of type of arguments, etc.)
  2. The C code supplies a variable or function argument of that type
  3. The C++ code populates the variable or passes an argument to the function that it creates by calling OSMemberFunctionCast (I guess normally on one of its own member functions)
  4. The C code can call that function like normal

OK, I'm handwaving there a little. I don't yet know how you call a function if you have a function pointer — but that seems like a much easier problem to solve.

I expect that I'll be using this in anger shortly, so there should be a working example coming soon.

<< Prev: Structs and Pointers       Next: Workqueues >>

4 comments:

  1. i am gathering this is a dead project now?

    ReplyDelete
  2. please revival this project.
    We hackintoshers want it so badly.
    if you accomplish this driver, you'll be remembered by many.

    ReplyDelete