in reply to returning an object in XS

By the way, *result = r; is wrong. You're writing to unallocated memory. You need to allocate a rect first, and place a pointer to it in result. That also means the code calling your function will have to free it, which makes it wholly inappropriate for an XS function to return this.

Sorry, don't know how to call C++ code from C, so I can't help you more than that.

Replies are listed 'Best First'.
Re^2: returning an object in XS
by bipham (Novice) on Feb 29, 2012 at 20:40 UTC

    Hi Ikegami, After I fixed it, it passed but then it gives me another error shown below

    *** glibc detected *** free(): invalid next size (fast): 0x000000000089aaa0 *** Abort

    I don't know what happen, would you please help? The code is posted below. By the way, is that possible you can scan thru my code to see if I am doing what I supposed to do?

    Thanks Ikehami,
    MODULE = nDB PACKAGE = geom REQUIRE: 1.925 SV* get_bbox(rects) SV* rects INIT: rect* result; rect** arrRects; I32 nRects = 0; SV* sv; SV* rv = newRV_noinc(sv); if (rv == NULL) warn("RV has not been created sucessfully!\n"); SV** ssv; double minx,miny,maxx,maxy,tmp_minx,tmp_miny,tmp_maxx,tmp_maxy; int n; if ((!SvROK(rects))||(SvTYPE(SvRV(rects)) != SVt_PVAV)||((nRects = +av_len((AV*)SvRV(rects))) < 0)) { XSRETURN_UNDEF; } arrRects = (rect**)safemalloc(sizeof(rect*)*(nRects)); for (n=0;n<=nRects;n++) { ssv = av_fetch((AV*)SvRV(rects), n, 0); if (ssv != NULL) { arrRects[n] = (rect*)malloc(sizeof(rect)); if (arrRects[n] == NULL) { warn("get_bbox: unable to malloc rect\n"); } else { arrRects[n] = (rect*)SvIV((SV*)SvRV(*ssv)); } } } CODE: minx = (*arrRects)->x1(); miny = (*arrRects)->y1(); maxx = (*arrRects)->x2(); maxy = (*arrRects)->y2(); for (n=1;n<=nRects;n++) { tmp_minx = (*(arrRects+n))->x1(); tmp_miny = (*(arrRects+n))->y1(); tmp_maxx = (*(arrRects+n))->x2(); tmp_maxy = (*(arrRects+n))->y2(); if (tmp_minx < minx) minx = tmp_minx; if (tmp_miny < miny) miny = tmp_miny; if (tmp_maxx > maxx) maxx = tmp_maxx; if (tmp_maxy > maxy) maxy = tmp_maxy; } result = (rect*)malloc(sizeof(rect*)); rect r(minx,miny,maxx,maxy); *result = r; sv_setref_iv(rv,"rect",(IV) result); RETVAL = rv; OUTPUT: RETVAL

      Oh I found it. The line

      result = (rect*)safemalloc(sizeof(rect*));

      should be

      result = (rect*)safemalloc(sizeof(rect));

      Regards,
Re^2: returning an object in XS
by bipham (Novice) on Feb 29, 2012 at 19:50 UTC

    Thanks Ikegami, I really appreciate your advice. I will fix this and see if it passed.