Thread overview
Linking D with C structs
Jun 29
Anthony
Jun 29
kinke
Jul 01
Anthony
June 29
Hello,


I'm trying to hand write some bindings to mongo-c-driver. (For learning purposes and to get the latest bindings).

My binding code to convert <mongoc/mongoc.h> to mongoc/mongoc.d is:

===== c interop file ====
module mongoc/mongoc.d;
import core.stdc.stdint;

extern (c) {
struct {
    uint domain;
    uint code;
    char[504] message; //when this exists, the code does not compile
}
}
=======================

===== build script ====

export LD_LIBRARY_PATH=mongo-c-driver/cmake-build/src/libmongoc:mongo-c-driver/cmake-build/src/libbson:$LD_LIBRARY_PATH

dmd hello_mongo.d \
    -I=mongo-c-driver/src/libmongoc/src/ \
    -I=mongo-c-driver/src/libbson/src/ \
    -I=mongo-c-driver/cmake-build/src/libbson/src/bson/ \
    -I=mongo-c-driver/cmake-build/src/libmongoc/src/mongoc \
    -L=-Lmongo-c-driver/cmake-build/src/libmongoc \
    -L=-Lmongo-c-driver/cmake-build/src/libbson \
    -L=-lmongoc-1.0 \
    -L=-lbson-1.0 \

./hello_mongo
========================


However, when I add the message field in the struct, I cannot compile the code:

ld: hello_mongo.o: in function `_Dmain':
hello_mongo.d:(.text._Dmain[_Dmain]+0x1a): undefined reference to `_D6mongoc6mongoc13_bson_error_t6__initZ'


What does "__initZ" refer to?
Does this refer to automatic initialization like "this()"?
June 29
On Monday, 29 June 2020 at 06:29:38 UTC, Anthony wrote:
> What does "__initZ" refer to?
> Does this refer to automatic initialization like "this()"?

Almost, it's the static initializer for that struct, which is omitted because you apparently don't compile/link the module containing the struct declaration. Initialize the char array with zeros (= 0) to make the struct fully zero-initialized, preventing the need for that symbol. chars in D are initialized with 0xFF, unlike byte and ubyte.
July 01
On Monday, 29 June 2020 at 10:44:16 UTC, kinke wrote:
> On Monday, 29 June 2020 at 06:29:38 UTC, Anthony wrote:
>> What does "__initZ" refer to?
>> Does this refer to automatic initialization like "this()"?
>
> Almost, it's the static initializer for that struct, which is omitted because you apparently don't compile/link the module containing the struct declaration. Initialize the char array with zeros (= 0) to make the struct fully zero-initialized, preventing the need for that symbol. chars in D are initialized with 0xFF, unlike byte and ubyte.

Thanks for this!

What do you mean by "which is omitted because you apparently don't compile/link the module containing the struct declaration"?

Is there a link step that I'm missing that will make things easier for me?
Is there a way to have D automatically get the struct from the c files directly?