A C/C++ interop library for the Nim programming language.
Similar to the nimline
library,
this library allows one to interop with C/C++ code without having to generate
wrappers with tools like nimterop
.
Unlike nimline
, cinterop
does not depend on Nim's experimental
dotOperators
feature and relies only on Nim's macro system to generate code.
- Provides convenience macros to declare C/C++ types and functions
(
decls.nim
). - Converts a subset of Nim to its syntactical equivalent in C/C++ without
requiring forward declarations for all types and functions involved in the
expression (
exprs.nim
).
See tests for examples of most features. This section provides an incomplete summary of the core functionality.
Say you have the following C++ class:
// simple.hpp
class CppClass1
{
public:
int field1 = 1;
int method1(int arg)
{
return 1 + arg;
}
};
You simply need to declare the C++ type and the source file it resides in:
# simple.nim
csource "simple.hpp":
type CppClass1* = object of CClass
and then you can access the fields and methods of that type:
# main.nim
var instance1 = CppClass1.init()
echo cexpr[cint]^instance1.field1 # prints "1"
cexpr[cint]^instance1.field1 = 2
echo cexpr[cint]^instance1.method1(instance1.field1) # prints "3"
Notice that cexpr[T]^
indicates the return type T
of the whole expression,
and only needs to be used at the beginning. This means that types for members do
not need to be declared, as long as the type of the variable whose members are
accessed is known.
Nim requires that the result of a function call with a return type must be used,
so if the result of a method is to be discarded, one can use the cexpr^
invocation, which is shorthand for cexpr[void]^
:
cexpr^instance1.method1(0)
If the type of a return value does not need to be known but is used in an
operation, one can use the cauto^
invocation like so:
cauto^instance1.field1 += 2
To simplify the mechanics of cexpr[T]^
, it is required on both sides of a
binary operation if both sides are C/C++ expressions:
cexpr[cint]^instance1.field1 += cexpr[cint]^instance1.field1
cauto^instance1.field1 += cexpr[cint]^instance1.field1 # same as above
cauto^instance1.field1 += cauto^instance1.field1 # same as above
This project is maintained during my free time, and serves as a tool for a game engine I am writing after work hours. Contributions are welcome, and will merge them immediately if they serve to keep the project robust, simple, and maintainable.
Cheers and happy coding! ๐บ