Updated Playing with CPP VTABLE from Nim (markdown)

This commit is contained in:
andri lim 2016-01-30 11:49:32 +07:00
parent d279471635
commit bd91e73617
1 changed files with 4 additions and 2 deletions

View File

@ -1,4 +1,4 @@
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?
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:
notepad++ plugin is a normal dll with normal interface. Standard notepad++ plugin requires standard cdecl calling convention for it's binary interface, not a big problem, Nim ffi can handle that perfectly. But things get more interesting when we want to make an external lexer for notepad++ editor engine: Scintilla.
@ -147,4 +147,6 @@ 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?, 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!
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.