1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

How to load and call shared objects from Python

Last updated at Posted at 2021-08-22

C言語で作った共有オブジェクトと連携してみる。

$ cat greeting.c

char *
getMessage (void)
{
  return "HELLO!";
}
void
sayHowRU ()
{
  printf ("Hi, how are you?\n");
}
int
getSquare (int i)
{
  return i * i;
}
int
multiplication (int a, int b)
{
  return a * b;
}
$ gcc -c greeting.c && gcc -shared -o greeting.so greeting.o
$ ls -l *.so
-rwxr-xr-x 1 kishi kishi 10638 May 25 19:54 greeting.so

$ cat MyProto.py
#!/usr/bin/env python

import ctypes

myLib = ctypes.CDLL( './greeting.so' )

"""
-- This is the case that the function has no arguments
getMessage = myLib.getMessage
getMessage.argtypes = [ctypes.c_void_p]
getMessage.restype = ctypes.c_char_p
print getMessage(None)
"""

#------------------------------------------------
# calls C function "getMessage()"
#------------------------------------------------
getMessage = myLib.getMessage
getMessage.restype = ctypes.c_char_p
print getMessage()
#------------------------------------------------
# calls C function "sayHello()"
#------------------------------------------------
sayHowRU = myLib.sayHowRU
sayHowRU()
#------------------------------------------------
# calls C function "getSquare()"
#------------------------------------------------
getSquare = myLib.getSquare
print getSquare(10)
#------------------------------------------------
# calls C function "multiplication()"
#------------------------------------------------
multi = myLib.multiplication
print multi(9,9)
$ ./MyProto.py
HELLO!
Hi, how are you?
100
81
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?