www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Problem with D calling C.

reply Bob Cowdery <bob bobcowdery.plus.com> writes:
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 7bit

Hi all,
I have a strange problem with D calling C.  I have written a small C
wrapper to the speex codec. In my application I was getting a
segmentation fault. Having done some tests if I test my wrapper from a
simple C main it works. If I test it from an equally simple D main it
seg faults. I have lots of other C code in my app which appears to work
fine. I've added the two blocks of calling code below and attached the
wrapper (hope that's allowed). It's all only test code at present so
forgive the mess.

Environment is Ubuntu 10.04, DMD Compiler V 2.050, and GCC for the C code.

'C' main
#include <stdio.h>
#include <stdlib.h>

extern int lib_speex_init();
extern int lib_speex_term();
extern int lib_speex_get_frame_sz();
extern int lib_speex_encode(short *samples, char*encoded_bytes);

int main()
{
    short smpls[640];
    char bytes[500];
    int r;
    lib_speex_init();
    r = lib_speex_encode(smpls, bytes);
    printf("Bytes written: %d\n", r);
    return 0;
}

'D' main
import std.stdio;
// In codec.c
extern (C) int lib_speex_init();
extern (C) int lib_speex_resample(short* smpls, int* in_sz, short*
resmpls, int* out_sz);
extern (C) int lib_speex_get_frame_sz();
extern (C) int lib_speex_encode(short *samples, char* encoded_bytes);

int main(char[][] args)
{
    short smpls[640];
    char bytes[500];
    int r;
    lib_speex_init();
    r = lib_speex_encode(cast(short*)smpls, cast(char*)bytes);
    writeln("Bytes written: ", r);
    return 0;
}
Jan 03 2011
parent bearophile <bearophileHUGS lycos.com> writes:
Bob Cowdery:

I don't know what your bug is, but this is bad D code:
     r = lib_speex_encode(cast(short*)smpls, cast(char*)bytes);

Use the "ptr" field of D arrays: r = lib_speex_encode(smpls.ptr, bytes.ptr); Bye, bearophile
Jan 03 2011