Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Inline::C and NULL pointers

by Chrysotoxum (Novice)
on Dec 19, 2021 at 11:38 UTC ( [id://11139725]=note: print w/replies, xml ) Need Help??


in reply to Inline::C and NULL pointers

Here's a little program illustrating one way of using undef as a 'NULL pointer' parameter in Inline C.

use strict; use warnings; my $point = pack 'f2', 1.2, 2.3; func(\$point); func(undef); # pass in 'NULL pointer' use Inline C => <<'C_END'; typedef struct { float x, y; } Point; void func(SV *buf) { SV *point_ref = SvRV(buf); if (!point_ref) { printf("got a null pointer\n"); } else { /* dereference */ Point *point = (Point *)SvPV_nolen(point_ref); printf("x=%.2f, y=%.2f\n", point->x, point->y); } } C_END

Hope this helps.

Replies are listed 'Best First'.
Re^2: Inline::C and NULL pointers
by etj (Deacon) on Dec 19, 2021 at 15:37 UTC
    Rather than requiring passing a reference, it would be better to just pass a normal scalar and use SvOK to see if it is defined rather than what looks a bit contrived with the SvRV. As it is, your code does not handle the case of a non-ref value.

      Just updated the program to take on board your helpful critique.

      use strict; use warnings; my $point = pack 'f2', 1.2, 2.3; func(undef); # pass in 'NULL pointer' func($pointer); Inline C => <<'C_END'; typedef struct { float x, y; } Point; void func(SV *buf) { if (!SvOK(buf)) { printf("got a null pointer\n"); } else if (SvPOK(buf) && SvCUR(BUF) == sizeof(Point)) { Point *point = (Point *)SvPV_nolen(buf); printf("x=%.2f, y=%.2f\n"); } else { croak("invalid scalar"); } } C_END
        Sorry to only just notice this (and thanks for the kind words)! I think your printf line needs two more args, point[0], point[1]?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11139725]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (3)
As of 2024-04-16 22:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found