Updated Playing with CPP VTABLE from Nim (markdown)

This commit is contained in:
andri lim 2016-01-30 11:53:26 +07:00
parent bd91e73617
commit c2993e5bf8
1 changed files with 5 additions and 3 deletions

View File

@ -1,3 +1,7 @@
### Precautions
This method have been tested to be interoperable between MS-VCC and GCC(MINGW) on Windows, and should be compatible with LLVM-clang too. But for other C++ compiler, there is no guarantee this method will work. So use it with cautions. Generally this is really unsafe assumption about how C++ compiler works. Don't rely on this explanation if you are not sure what really happened under the hood. Better wrap the virtual functions call in an extern "C" function and call that from Nim if you want to be sure the compiler generate correct virtual functions call.
### The Situation
Imagine you are trying to communicate with a C++ app from Nim, and the C++ interface only provide a bunch of pure virtual functions classes, and a pointer to the class instance. Only a few `extern "C"` functions to initialize the communication, all other communications must be done via that pointer. What will you do?
### Case example, notepad++ plugin:
@ -147,6 +151,4 @@ Again, we can see how actually C++ compilers translate `->` operator when callin
### Conclusion
That's it, not too difficult heh? It's not too difficult because we are not dealing with C++ name mangling here, only dealing with pointers and calling convention, Nim can handle that perfectly, although a bit verbose compared to C++ style.
What about C++ ordinary [member] functions, constructor, and destructor?, well that's another story, C++ name mangling can be a nightmare if you try to solve that in Nim, because every C++ compiler have their own flavor/style of name mangling, but if you know the exact formula of C++ name mangling, please write another wiki!
This method have been tested to be interoperable between MS-VCC and GCC(MINGW) on Windows, and should be compatible with LLVM-clang too. But for other C++ compiler, there is no guarantee this method will work. So use it with cautions. Generally this is really unsafe assumption about how C++ compiler works. Don't rely on this explanation if you are not sure what really happened under the hood.
What about C++ ordinary [member] functions, constructor, and destructor?, well that's another story, C++ name mangling can be a nightmare if you try to solve that in Nim, because every C++ compiler have their own flavor/style of name mangling, but if you know the exact formula of C++ name mangling, please write another wiki!