Just wanted to add, you can test this using the following:
gcc -shared -o struct_test.so -fPIC struct_test.c
nim c -r struct_test.nim
Hi Araq, thanks for your quick reply, the .bycopy pragma worked! Now I have two questions:
Am I using c2nim wrong? You suggested that c2nim would add the bycopy pragma, but c2nim generates this:
type
MyStruct* = object
id*: cuint
width*: cint
height*: cint
mipmaps*: cint
format*: cint
The other question is that if I change width/height to floats, the output is wrong again:
struct_test.nim:
type
MyStruct* {.bycopy.} = object
id*: cuint
width*: cfloat
height*: cfloat
mipmaps*: cint
format*: cint
#*rest of file*
struct_test.c:
typedef struct MyStruct {
unsigned int id;
float width;
float height;
int mipmaps;
int format;
} MyStruct;
output:
from nim: testStruct.width 2.0
from nim: testStruct.height 3.0
from c: testStruct.width 1473414672
from c: testStruct.height 1473414672
Am I using c2nim wrong?
No, but an outdated version of c2nim. ;-)
The other question is that if I change width/height to floats, the output is wrong again
Huh, this makes no sense, there is nothing wrong with your snippets. Maybe give us a full example program?
outdated version of c2nim
Doh! You are correct :)
there is nothing wrong with your snippets
Ah, you are correct again. I forgot to change %d to %f in my C file
Thanks for the help!
I usually do it like this
mystruct.h:
typedef struct MyStruct {
int width, length, mipmaps, pixels;
} MyStruct;
mystruct.c:
#include <stdio.h>
#include "mystruct.h"
void printMyStruct(MyStruct ms) {
printf("from c\t: test.width %d\n, ms.width);
printf("from c\t: test.length %d\n, ms.length);
}
caller.nim:
{.passC: "-I.".}
type
MyStruct {.header: "\"mystruct.h\"", importc: "MyStruct".} = object
width, length, mipmaps, pixels: cint
proc printMyStruct(ms: MyStruct)
{.importc: "printMyStruct", dynlib:"./mystruct.dll".}
var ms = MyStruct(width: 5.cint, length: 7.cint)
echo "from nim: test.width ", ms.width
echo "from nim: test.length ", ms.length
printMyStruct(ms)
compile:
gcc -shared -o mystruct.dll -fPIC mystruct.c
nim c -r caller
I'm not really sure there.
From the manual, the importc pragma is about name mangling while the bycopy pragma is to instruct compiler pass-by-value to procs.
For some lib that I converted using c2nim, the objects were without any pragma, and I just adjusted the procs to properly have headers and it's done.