PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 25, 2022

[FIXED] How can I import so file as a module without using ctype Linux?

 August 25, 2022     linux, module, python, shared-libraries     No comments   

Issue

File structure under folder /home/cyan/TEMP

test.py
  
lib
 |--libc_test_module.so
 
c_test_module.cc
 
CMakeLists.txt

test.py

import sys
sys.path.append("/home/cyan/TEMP/lib") 
import c_test_module

c_test_module.cc

#include <Python.h>

int c_test_function(int a) {
    return a + 1;
}

static PyObject * _c_test_function(PyObject *self, PyObject *args)
{
    int _a;
    int res;

    if (!PyArg_ParseTuple(args, "i", &_a))
        return NULL;
    res = c_test_function(_a);
    return PyLong_FromLong(res);
}


/*  define functions in module */
static PyMethodDef TestMethods[] =
{
     {"c_test_function", _c_test_function, METH_VARARGS,
         "this is a c_test_function"},
     {NULL, NULL, 0, NULL}
};


static struct PyModuleDef c_test_module = {
    PyModuleDef_HEAD_INIT,
    "c_test_module", "Some documentation",
    -1,
    TestMethods
};
PyMODINIT_FUNC PyInit_c_test_module(void) {
    PyObject *module;
    module = PyModule_Create(&c_test_module);
    if(module==NULL) return NULL;
    /* IMPORTANT: this must be called */
    import_array();
    if (PyErr_Occurred()) return NULL;
    return module;
}

Error

ModuleNotFoundError: No module named 'c_test_module'

Question

I don't want to use ctype module to import .so file. Instead, I wonder if there is a way to import this file as a module directly.


Solution

I created a setup.py file:

from distutils.core import setup, Extension
import numpy

def main():
    setup(name="c_test_module",
          version="1.0.0",
          description="Python interface for the c_test_module C library function",
          author="cyan",
          author_email="xxx@gmail.com",
          ext_modules=[Extension("c_test_module", ["c_test_module.cc"],
                                include_dirs=[numpy.get_include()])],
    )

if __name__ == "__main__":
    main()

Now it works to import c_test_module and call the functions.



Answered By - Cyan
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,205,917

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing