I posted the following wanting to experiment with the foriegn functin interface in SBCL. Several good comments came forth. I left out something I didn't understand to be important. My problem working the example seems to be because I am using a Mac. I just went through the example on a Linux system and it worked beautifully. So, the problem is really a Mac setup problem. The SBCL manual example does work. I am going to have to go back to my Mac and figure out how to set it up. By the way, the loader uses the -shared option to get this to work. Mac doesn't use shared, so there may be some workarounds needed in the setup.
Thanks to all who reviewed the question.
==== Original Question ====
I am interested in using Common Lisp (SBCL) and executing some functions written in C. I found the section 9.9 in the SBCL User Manual https://www.sbcl.org/manual/#Step_002dBy_002dStep-Example-of-the-Foreign-Function-Interface which looked like a great start.
A few problems already. The C code is somewhat defective, I think. It wouldn't compile, not finding definitions. I figured out I needed to add #include for <stdio.h> and <stdlib.h>. The compiler worked but spit out a warning:
Here is the C code:
#include <stdio.h>
#include <stdlib.h>
struct c_struct
{
int x;
char *s;
};
struct c_struct *c_function (i, s, r, a)
int i;
char *s;
struct c_struct *r;
int a[10];
{
int j;
struct c_struct *r2;
printf("i = %d\n", i);
printf("s = %s\n", s);
printf("r->x = %d\n", r->x);
printf("r->s = %s\n", r->s);
for (j = 0; j < 10; j++) printf("a[%d] = %d.\n", j, a[j]);
r2 = (struct c_struct *) malloc (sizeof(struct c_struct));
r2->x = i + 5;
r2->s = "a C string";
return(r2);
};
Here is the warning from compilation:
test.c:10:18: warning: a function definition without a
prototype is deprecated in all versions of C and is
not supported in C2x [-Wdeprecated-non-prototype]
struct c_struct *c_function (i, s, r, a)
^
1 warning generated.
Forging ahead, I ran the linker and got errors:
lisptest % ld -o test.so test.o
ld: Undefined symbols:
_main, referenced from:
<initial-undefines>
_malloc, referenced from:
_c_function in test.o
_printf, referenced from:
_c_function in test.o
_c_function in test.o
_c_function in test.o
_c_function in test.o
_c_function in test.o
lisptest %
I'm not a C nor an Objective C programmer (but will be in a bit, I believe). I'd like to get the example working. When it does I'll send a change request to sbcl.org to fix up the example, but I need help moving ahead.
What is needed to resolve the linker references? Does the C code need to be updated?