Let's assume that there's a class called `MyClass`.
{.emit: """
class MyClass {
public:
int a;
int MyMethod();
}
""".}
type MyClass {.importcpp, nodecl.} = object
a: cint
Run
To implement one of its methods, we can use the undocumented pragma
`{.exportcpp.}`. There's still some problems to overcome because Nim generates
a declaration for every proc before its implement, which will cause an error.
You have to tell the compiler to ignore the first declaration. And the pointer
`this` need to be imported.
proc MyMethod(): cint {.
exportcpp: "MyClass::MyMethod",
codegenDecl: """
#ifdef MyMethod_SHOULD_BE_DEFINED
int MyClass::MyMethod()
#else
#define MyMethod_SHOULD_BE_DEFINED
#endif
""".} =
var this {.nodecl, importc, global.}: ptr MyClass
#Use {.nodecl, importc, global.} because {.nodecl.} doesn't work on local
variables
return (this[]).a
Run
After that, you may import its correct form so that it can be used normally.
proc MyMethod(self: MyClass): cint {.importcpp: "#.$1(@)", nodecl.}
var foo: MyClass
echo foo.MyMethod()
Run