[Cuis-dev] FFI example

Mark Volkmann r.mark.volkmann at gmail.com
Mon Sep 30 08:09:35 PDT 2024


Vanessa's getenv example works for me. Now I want to learn how to invoke my
own C functions.
I created the file "mylib.c" containing this:

char* greet() {
  return "Hello, World!";
}

Then I created a shared library for macOS with this:

clang -dynamiclib -o libmylib.dylib mylib.c

Then I created this Smalltalk class:

ExternalLibrary subclass: #FFIDemo
    instanceVariableNames: ''
    classVariableNames: ''
    poolDictionaries: ''
    category: 'Volkmann'

Then I added this class method:

greet
    <cdecl: char* 'greet' () module:
'/Users/volkmannm/Documents/dev/lang/smalltalk/Cuis-Smalltalk-Volkmann/libmylib.dylib'>
    ^self externalCallFailed

Side note: I need to learn where this looks by default for shared libraries
so I don't have to specify an absolute path.

Then I entered this in a Workspace and did a "Print it".

FFIDemo greet

That opens a Debug window with the message "Error: Unable to find function
address".

Can anyone spot where I'm going wrong?

On Sun, Sep 29, 2024 at 10:10 PM Andres Valloud via Cuis-dev <
cuis-dev at lists.cuis.st> wrote:

> Except of course getenv() is ruled by POSIX so doing that is at the very
> least not portable, if not outright wrong.
>
> On 9/29/24 6:29 PM, Vanessa Freudenberg via Cuis-dev wrote:
> > And, defining a method myself works fine:
> >
> > getenv: var
> >          <cdecl: char* 'getenv' (char*) module: 'libSystem.dylib'>
> >          ^self externalCallFailed
> >
> > And then
> >
> >     MyClass getenv: 'HOME'
> >
> >
> > returns
> >
> >       '/Users/vanessa' .
> >
> >
> > There really isn't much more to it.
> >
> > Vanessa
> >
> > On Sun, Sep 29, 2024 at 6:26 PM Vanessa Freudenberg
> > <vanessa at codefrau.net <mailto:vanessa at codefrau.net>> wrote:
> >
> >     I just loaded the "Tests-FFI" package and it works.
> >
> >     And you can e.g. run
> >
> >           FFITestLibrary new ffiTestFloats: 3 with: 4
> >
> >     which returns 7.0 because the plugin happens to implement
> >     "ffiTestFloats()" as returning the sum of its two arguments.
> >
> >     Vanessa
> >
> >
>
> --
> Cuis-dev mailing list
> Cuis-dev at lists.cuis.st
> https://lists.cuis.st/mailman/listinfo/cuis-dev
>


-- 
R. Mark Volkmann
Object Computing, Inc.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.cuis.st/mailman/archives/cuis-dev/attachments/20240930/c4fae503/attachment.htm>


More information about the Cuis-dev mailing list