Skip to content

Instantly share code, notes, and snippets.

@zhuomingliang
Forked from jnthn/foo.c
Created November 28, 2011 13:25
Show Gist options
  • Save zhuomingliang/1400388 to your computer and use it in GitHub Desktop.
Save zhuomingliang/1400388 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
__declspec(dllexport) void Argless()
{
printf ("Hello from argless function!\n");
}
__declspec(dllexport) void GotValues(int x, float y, char *z1)
{
printf ("Hello from DLL; have %d, %f and %s\n", x, y, z1);
}
struct foo {
double x;
long long y;
double z;
};
__declspec(dllexport) void WithStruct(struct foo *s)
{
printf ("Got struct with %f, %d, %f\n", s->x, s->y, s->z);
}
__declspec(dllexport) void IDiddleTheStruct(struct foo *s)
{
s->x = 99.99;
}
__declspec(dllexport) char * ReturnAString()
{
return "A string from C!";
}
__declspec(dllexport) struct foo * ReturnAStruct()
{
struct foo *f = malloc(sizeof(struct foo));
f->x = 123.45;
f->y = 101;
f->z = 789.10;
return f;
}
use NativeCall;
##
## Some simple calls.
##
sub Argless() is native('foo.dll') { * }
Argless();
sub GotValues(int, num32, Str) is native('foo.dll') { * }
GotValues(42, 1.23e0, 'oh hai');
##
## Declare a class with C structure representation and pass it.
##
class foo is repr('CStruct') {
has num $.x;
has int $.y;
has num $.z;
method set(num $x, int $y, num $z) {
$!x = $x;
$!y = $y;
$!z = $z;
}
}
sub WithStruct(foo) is native("foo.dll") { * }
my $s = foo.new();
$s.set(2.5e0, 42, 10.1e0);
WithStruct($s);
sub IDiddleTheStruct(foo) is native("foo.dll") { * }
say "Before: $s.x()";
IDiddleTheStruct($s);
say "After: $s.x()";
##
## We can get string and struct return values.
##
sub ReturnAString() returns Str is native("foo.dll") { * }
say ReturnAString();
sub ReturnAStruct() returns foo is native("foo.dll") { * }
my $rs = ReturnAStruct();
say "Got back struct with $rs.x(), $rs.y(), $rs.z()";
##
## Example of calling the Windows API.
##
sub MessageBoxA(Int, Str, Str, Int) returns Int is native('user32.dll') { * }
say "MessageBoxA returned " ~ MessageBoxA(0, "Hi from Rakudo", "NCI", 0x40);
Hello from argless function!
Hello from DLL; have 42, 1.230000 and oh hai
Got struct with 2.500000, 42, 10.100000
Before: 2.5
After: 99.99
A string from C!
Got back struct with 123.45, 101, 789.1
MessageBoxA returned 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment