I'm currently using Python 3.7 and Pycharm for my work. Recently I got a code that is done at Python2.7

You shouldn't use Python 3.7 to run code that was written for Python 2.x, unless you can port that code to Python 3, or you know that it works fine. There are some caveats, and it depends on what the functionality of that code is. In some cases it might be very time consuming to convert it. 2to3 might help here.

So, depending on your use case, you may want to keep a legacy version of Python 2.7 around on your system to run that particular code, but note that Python 2.x will not get any (security) updates anymore, so you're better off using Python 3 from now on.

Try running the code in Python 3.7 and see if it works.

and it includes a library named 'ctypes.'

This is included by default in Python, so you don't need to install anything. Assuming you have the correct Python 2.7 interpreter and all other required packages, the code should just run fine as-is.

If the person who wrote the code was doing a good job, he or she should have left a README and/or a requirements.txt file or something similar that would specify which other packages or libraries are needed to run it.

Answer from slhck on Stack Exchange
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ ctypes.html
ctypes โ€” A foreign function library for Python
Source code: Lib/ctypes ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these ...
๐ŸŒ
Pkgs.org
pkgs.org โ€บ download โ€บ python-ctypes
Python-ctypes Download for Linux (deb, rpm)
Download python-ctypes packages for Amazon Linux, CentOS, Debian, Mageia, OpenMandriva, openSUSE, OpenWrt, PCLinuxOS, Ubuntu
Discussions

python - Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing - Stack Overflow
In my case what was causing all sorts of Python installation issues including the one having to do with _ctypes and libffi was Homebrew on Linux / Linuxbrew. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Installing ctypes
ctypes comes preinstalled with python. Did you try using it and it didn't work? Paste the code and the full error message you are getting. More on reddit.com
๐ŸŒ r/learnpython
9
1
November 2, 2022
How to install ctypes module for python 3.7 to be used with VSCode debugger - Stack Overflow
I have multiple python interperters in my computer 3.7 and 3.8. When I debug using with python 3.8 I do not face any issues using VSCode. My VScode python debugger fails when trying to debug with python 3.7. How do I install ctypes for python 3.7? More on stackoverflow.com
๐ŸŒ stackoverflow.com
Installation issue, linking Python with libffi to build ctypes module
Dear more experienced people, I am trying to install Python on a Linux cluster, running RHEL7. I need this to work two specific modules. One is Open3d, and the other is ctypes. Open3d requires a Python version earlier than 3.8. Recommended is 3.7.7, so I am using that one. More on discuss.python.org
๐ŸŒ discuss.python.org
0
1
July 21, 2023
Top answer
1 of 2
2

I'm currently using Python 3.7 and Pycharm for my work. Recently I got a code that is done at Python2.7

You shouldn't use Python 3.7 to run code that was written for Python 2.x, unless you can port that code to Python 3, or you know that it works fine. There are some caveats, and it depends on what the functionality of that code is. In some cases it might be very time consuming to convert it. 2to3 might help here.

So, depending on your use case, you may want to keep a legacy version of Python 2.7 around on your system to run that particular code, but note that Python 2.x will not get any (security) updates anymore, so you're better off using Python 3 from now on.

Try running the code in Python 3.7 and see if it works.

and it includes a library named 'ctypes.'

This is included by default in Python, so you don't need to install anything. Assuming you have the correct Python 2.7 interpreter and all other required packages, the code should just run fine as-is.

If the person who wrote the code was doing a good job, he or she should have left a README and/or a requirements.txt file or something similar that would specify which other packages or libraries are needed to run it.

2 of 2
0

This S.O question has an answer which says

You don't need to install ctypes at all; it is part of the Python standard library, as of Python 2.5 onwards. See the module documentation.

which was provided by @MartijnPieters who has over 700k rep and so, presumably, knows what he is talking about.

๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ ctypes
ctypes ยท PyPI
ctypes is a Python package to create and manipulate C data types in Python, and to call functions in dynamic link libraries/shared dlls.
      ยป pip install ctypes
    
Published ย  May 15, 2007
Version ย  1.0.2
Find elsewhere
๐ŸŒ
Readthedocs
gpib-ctypes.readthedocs.io โ€บ en โ€บ latest โ€บ installation.html
Installation โ€” gpib-ctypes 0.1.0dev documentation
This is the preferred method to install gpib-ctypes, as it will always install the most recent stable release. If you donโ€™t have pip installed, this Python installation guide can guide you through the process.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Installation issue, linking Python with libffi to build ctypes module - Python Help - Discussions on Python.org
July 21, 2023 - Dear more experienced people, I am trying to install Python on a Linux cluster, running RHEL7. I need this to work two specific modules. One is Open3d, and the other is ctypes. Open3d requires a Python version earlier than 3.8. Recommended is 3.7.7, so I am using that one.
๐ŸŒ
CodersLegacy
coderslegacy.com โ€บ home โ€บ python โ€บ how to install ctypes in python
How to Install ctypes in Python - CodersLegacy
July 8, 2022 - If you are using a really old version of Python or you uninstalled your old ctypes installation, you can use pip to install it. Just execute the following command in the terminal or command prompt of your system. ... If this command runs without throwing any errors, that means ctypes was installed on your system safely. If you want to learn more about ctypes and how to use it to write fast and efficient code, refer to our tutorial on ctypes. If you have a Linux/Ubuntu based OS, and you do not have pip installed on it, here is an alternative method for you to install ctypes.
๐ŸŒ
Red Hat
access.redhat.com โ€บ documentation โ€บ en-us โ€บ red_hat_enterprise_linux โ€บ 5 โ€บ html โ€บ 5.8_technical_notes โ€บ python-ctypes
3.6. RHEA-2012:0183 โ€” new package: python-ctypes | 5.8 Technical Notes | Red Hat Enterprise Linux | 5 | Red Hat Documentation
This enhancement update adds the python-ctypes package to Red Hat Enterprise Linux 5. (BZ#601661) ... This package is being added as a dependency of the iotop package. All users who require python-ctypes are advised to install this new package.
๐ŸŒ
DevManuals
devmanuals.net โ€บ install โ€บ ubuntu โ€บ ubuntu-16-04-LTS-Xenial-Xerus โ€บ how-to-install-python-ctypeslib.html
How to install python-ctypeslib On Ubuntu 16.04 Lts? Uninstall and remove python-ctypeslib Package
Learn how to uninstall and completely remove the package python-ctypeslib from Ubuntu 16.04 LTS Operating System. ... Above command will download the package lists for Ubuntu 16.04 on your system. This will update the list of newest versions of packages and its dependencies on your system. After downloading the latest package list with the help of above you can run the installation process.
๐ŸŒ
Anaconda.org
anaconda.org โ€บ conda-forge โ€บ pywin32-ctypes
pywin32-ctypes - conda-forge | Anaconda.org
Install pywin32-ctypes with Anaconda.org. A limited subset of pywin32 re-implemented using ctypes (or cffi)
๐ŸŒ
Python
bugs.python.org โ€บ issue31652
Issue 31652: make install fails: no module _ctypes - Python tracker
September 30, 2017 - This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide ยท This issue has been migrated to GitHub: https://github.com/python/cpython/issues/75833
๐ŸŒ
DEV Community
dev.to โ€บ ajkerrigan โ€บ homebrew-pyenv-ctypes-oh-my-3d9
Homebrew, pyenv, ctypes... oh my! - DEV Community
January 4, 2022 - CC="$(brew --prefix gcc)/bin/gcc-11" \ pyenv install --verbose 3.10.0 ยท And yes, that still worked. But why? The next step was to drop down a level and use python-build to set up side-by-side build directories: one working, one broken. To get a broken one, I used: ... From the broken directory, I could run make and see the ctypes warning. I could also see the object file renamed to ..._failed.so: โฏ fd "ctypes.*so" build/lib.linux-x86_64-3.10/_ctypes.cpython-310-x86_64-linux-gnu_failed.so build/lib.linux-x86_64-3.10/_ctypes_test.cpython-310-x86_64-linux-gnu.so
Top answer
1 of 4
279

Here's a quick and dirty ctypes tutorial.

First, write your C library. Here's a simple Hello world example:

testlib.c

#include <stdio.h>

void myprint(void);

void myprint()
{
    printf("hello world\n");
}

Now compile it as a shared library (mac fix found here):

$ gcc -shared -Wl,-soname,testlib -o testlib.so -fPIC testlib.c

# or... for Mac OS X 
$ gcc -shared -Wl,-install_name,testlib.so -o testlib.so -fPIC testlib.c

Then, write a wrapper using ctypes:

testlibwrapper.py

import ctypes

testlib = ctypes.CDLL('/full/path/to/testlib.so')
testlib.myprint()

Now execute it:

$ python testlibwrapper.py

And you should see the output

Hello world
$

If you already have a library in mind, you can skip the non-python part of the tutorial. Make sure ctypes can find the library by putting it in /usr/lib or another standard directory. If you do this, you don't need to specify the full path when writing the wrapper. If you choose not to do this, you must provide the full path of the library when calling ctypes.CDLL().

This isn't the place for a more comprehensive tutorial, but if you ask for help with specific problems on this site, I'm sure the community would help you out.

PS: I'm assuming you're on Linux because you've used ctypes.CDLL('libc.so.6'). If you're on another OS, things might change a little bit (or quite a lot).

2 of 4
78

The answer by Chinmay Kanchi is excellent but I wanted an example of a function which passes and returns a variables/arrays to a C++ code. I though I'd include it here in case it is useful to others.

Passing and returning an integer

The C++ code for a function which takes an integer and adds one to the returned value,

extern "C" int add_one(int i)
{
    return i+1;
}

Saved as file test.cpp, note the required extern "C" (this can be removed for C code). This is compiled using g++, with arguments similar to Chinmay Kanchi answer,

g++ -shared -o testlib.so -fPIC test.cpp

The Python code uses load_library from the numpy.ctypeslib assuming the path to the shared library in the same directory as the Python script,

import numpy.ctypeslib as ctl
import ctypes

libname = 'testlib.so'
libdir = './'
lib=ctl.load_library(libname, libdir)

py_add_one = lib.add_one
py_add_one.argtypes = [ctypes.c_int]
value = 5
results = py_add_one(value)
print(results)

This prints 6 as expected.

Passing and printing an array

You can also pass arrays as follows, for a C code to print the element of an array,

extern "C" void print_array(double* array, int N)
{
    for (int i=0; i<N; i++) 
        cout << i << " " << array[i] << endl;
}

which is compiled as before and the imported in the same way. The extra Python code to use this function would then be,

import numpy as np

py_print_array = lib.print_array
py_print_array.argtypes = [ctl.ndpointer(np.float64, 
                                         flags='aligned, c_contiguous'), 
                           ctypes.c_int]
A = np.array([1.4,2.6,3.0], dtype=np.float64)
py_print_array(A, 3)

where we specify the array, the first argument to print_array, as a pointer to a Numpy array of aligned, c_contiguous 64 bit floats and the second argument as an integer which tells the C code the number of elements in the Numpy array. This then printed by the C code as follows,

1.4
2.6
3.0
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ ctypes-callable
ctypes-callable
JavaScript is disabled in your browser. Please enable JavaScript to proceed ยท A required part of this site couldnโ€™t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser