why adding extern(C) cause a runtime error?

Dav1d via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jul 11 01:52:47 PDT 2015


On Saturday, 11 July 2015 at 01:22:14 UTC, mzfhhhh wrote:
> win7   x86  dmd2.067.1 ok
> ubuntu x64  dmd2.067.1 error
> -------------------------------------
> import std.stdio;
> import std.socket;
>
> extern(C)
> void recv()
> {
>     writeln("recv...");
> }
>
> extern(C)
> void send()
> {
>     writeln("send...");
> }
>
>
> int main(string[] argv)
> {
>     //copy from std.socket unittest
>
>     immutable ubyte[] data = [1, 2, 3, 4];
>     auto pair = socketPair();
>     scope(exit) foreach (s; pair) s.close();
>
>     pair[0].send(data);
>
>     auto buf = new ubyte[data.length];
>     pair[1].receive(buf);
>     assert(buf == data);
>
>     return 0;
> }
> ----------------------------------
> send...
> recv...
> core.exception.AssertError at a.d(27): Assertion failure
> ----------------
> ./a() [0x43d61f]
> ./a(_Dmain+0xcc) [0x43d1bc]
> ./a(_D2rt6dmain211_d_run_mainUiPPaPUAAaZiZ6runAllMFZ9__lambda1MFZv+0x1f) [0x4400fb]
> ./a(void rt.dmain2._d_run_main(int, char**, extern (C) int 
> function(char[][])*).tryExec(scope void delegate())+0x2a) 
> [0x44004e]
> ./a(void rt.dmain2._d_run_main(int, char**, extern (C) int 
> function(char[][])*).runAll()+0x30) [0x4400b4]
> ./a(void rt.dmain2._d_run_main(int, char**, extern (C) int 
> function(char[][])*).tryExec(scope void delegate())+0x2a) 
> [0x44004e]
> ./a(_d_run_main+0x1dc) [0x43ffc8]
> ./a(main+0x17) [0x43d637]
> /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5) 
> [0x7f5fabd8fec5]

You basically "overwrite" the C send(2) and recv(2) functions 
with your code (the actual symbols, the linker will yours instead 
the "real" ones). So std.socket doesn't call the C functions but 
yours. Yours obviously don't send and receive data. If you really 
want to "overwrite" these functions you might be able to call the 
original ones via dlsym.



More information about the Digitalmars-d-learn mailing list