Python ctypes Tutorial - Using C/C++ Functions in Python

  Рет қаралды 47,529

CodersLegacy

CodersLegacy

2 жыл бұрын

Python as a Programming Language is slower and less efficient in comparison to languages like C and C++. Writing certain parts of your code in C/C++ can significantly improve your performance. The ctypes library creates an interface which allows you to import C/C++ functions and execute them in Python.
C File Compilation Command:
gcc -fPIC -shared -o clibrary.so clibrary.c
Website Link: coderslegacy.com/python/ctype...
Related Links:
Ctypes Basics: • Python ctypes Tutorial...
Ctypes Datatypes and Strings: • Python ctypes Library ...
Ctypes Pointers: • Introducing Pointers i...
Ctypes with C++: • Ctypes Library - How t...

Пікірлер: 49
@user-bm7bd8jv4w
@user-bm7bd8jv4w 17 күн бұрын
Well done. I have never seen videos like this. Thank you very much
@iancu_de_hunedoara
@iancu_de_hunedoara 10 ай бұрын
after 2.5 hours of searching, I finally found adequate tutorial.
@NickSBailey
@NickSBailey Жыл бұрын
great this is exactly what I've been looking for and clearly explained
@MnemonicCarrier
@MnemonicCarrier 11 ай бұрын
Nice quick how-to - very informative, thanks!
@malborboss
@malborboss Жыл бұрын
Video is very informative although the way "Okay" keeps being repeated is a little bit iritating
@andrewhenson8458
@andrewhenson8458 Жыл бұрын
I was thinking the same thing. Great video, but the "okay"s were distracting. OP, please opt for silence, much better than filler words (for the viewers)
@Jayveersinh_Raj
@Jayveersinh_Raj Ай бұрын
The reason why only J was printed and no john before converting into bytes is that when declared in the function as pointer, by default it only points to the 0th value, this is done for efficiency in c, hence, you do not pass entire array right away. You can increment the pointer and get the entire array (string "john") by incrementing pointer in the c function, that would be faster than converting it to bytes first.
@undeadpresident
@undeadpresident Жыл бұрын
This was explained well. I got to try this. I've been wanting to become proficient in C and speed up the python program I'm working on, but don't have time to go full bore into rewriting the whole thing in C. Maybe I can do it piece by piece and see how it goes.
@falalafel8142
@falalafel8142 Жыл бұрын
Hey man, thanks for the great video!
@enrique4322
@enrique4322 Жыл бұрын
hiii!! do you know how in python , load a Third part DLL , I´ve just only has documentation of the Methods of the DLL, but I do not Know what is inside. COuld you guide me? please
@csd4ni3l
@csd4ni3l 2 жыл бұрын
thanks this is what i wanted to learn because i use python libraries that use c libraries
@retrojames4226
@retrojames4226 3 ай бұрын
I write DLL's in Pascal. This has been useful to me thank you.
@rahultheytv5347
@rahultheytv5347 11 ай бұрын
what is the command for windows
@JimniDas-cj2yl
@JimniDas-cj2yl 9 ай бұрын
Thank you so much sir!
@haxidenti6001
@haxidenti6001 Ай бұрын
Would be good to see working with pointers and structure
@MatthijsKoelewijn
@MatthijsKoelewijn Жыл бұрын
I got this error : OSError: [WinError 193] %1 is not a valid Win32 application Can anyone help me out?
@valsk01
@valsk01 Жыл бұрын
@@YounesLab thanks mate
@shuryimaziz3426
@shuryimaziz3426 6 ай бұрын
@@valsk01what did they say
@valsk01
@valsk01 6 ай бұрын
@@shuryimaziz3426 i not sure... idk why he deleted it :(
@Vnifit
@Vnifit 6 ай бұрын
For anyone in the future this occurs because you need to compile your program into 64-bit. I had MinGW installed and it uses 32-bit and compiles 32-bit so even if you use the -m64 flag with the gcc command it doesn't work. I had to delete the C:/MinGW folder and path environment variable, then install the x86_64 version of Cygwin, then install the gcc-core package (which installs gcc). Then I had to add C:/cygwin64/bin to my path environment variable so the command would be recognized. Then I just compiled binaries with this command (where function.c was my .c file to compile): gcc -m64 -shared -o function.dll function.c Hope this helps.
@AlekseyHmelevskoy
@AlekseyHmelevskoy 4 ай бұрын
function 'display' not found ((((
@ankidokolo
@ankidokolo Жыл бұрын
Hi. Thank you for the tutorial. It was great. I am just trying to get a numerical result from function in c to my python code. If the number is big (thousands or millions) it cannot be displayed in the python output, although it works just fine in the c code. Is there any way to make python or ctypes show such numbers.
@coderslegacy5661
@coderslegacy5661 Жыл бұрын
Sounds like a datatype issue. Are you using regular integers, or are you using the ctypes datatypes like longlong which have a much larger range of values. If not, switch to using those.
@ankidokolo
@ankidokolo Жыл бұрын
@@coderslegacy5661 Hi. After carfully looking for problems, I found out that I hadn't actually had this problem I mentioned above. I already got the right answer, but not showing it in the right place was because python doesn't show the results from the called c function until the exit time. My code(s) ends with a graph plotting, however only after I close the plot window (of matplotlib) and the program terminates, it shows the results from the c function, although in the code itself executing the ctype thing should come first because it is at the beginning of the code. So, It's like python delays the execution of any ctypes till the end at the exit-time. I have tried it with many cases and codes. The same happens every single time. And this is, I think, a weak point in ctypes.
@maksimluzin1121
@maksimluzin1121 9 ай бұрын
@@ankidokolo , The problem is probably related to the Python GIL. Try to isolate C-calls into separate Python-functions, it may provide some 'hints' for the Python interpreter... Another problem could be the Mathlib/Matplotlib themselves written in C and calls to different C-libraries could be organized in a sequential way in Python... Just my versions!
@ReinventedWeb
@ReinventedWeb 2 жыл бұрын
Cool video
@RAGHAVJAIN-um3ou
@RAGHAVJAIN-um3ou Ай бұрын
can someone please help me with this error, followed the tutorials but still getting this error, Traceback (most recent call last): File "c:\Users agha\OneDrive\Desktop\test\main.py", line 2, in clibrary = ctypes.windll.LoadLibrary("C:\\Users\ agha\\OneDrive\\Desktop\\test\\clibrary.dll") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users agha\AppData\Local\Programs\Python\Python312\Lib\ctypes\__init__.py", line 460, in LoadLibrary return self._dlltype(name) ^^^^^^^^^^^^^^^^^^^ File "C:\Users agha\AppData\Local\Programs\Python\Python312\Lib\ctypes\__init__.py", line 379, in __init__ self._handle = _dlopen(self._name, mode) ^^^^^^^^^^^^^^^^^^^^^^^^^ OSError: [WinError 193] %1 is not a valid Win32 application
@tootyfruity8
@tootyfruity8 Жыл бұрын
I've copied your code up until 6:57 where I call clibrary's display function, but my thing wont run ;( It just says "AttributeError: function 'display' not found"--what do you think went wrong im sure ive done ive copied you correctly. My third line of code ran just fine
@coderslegacy5661
@coderslegacy5661 Жыл бұрын
Did you recompile your C/C++ code after your added the display function? You might also want to make sure your file paths are correct, and the Python code is locating the shared file properly.
@jaksiz
@jaksiz 4 ай бұрын
Thank you
@CsAlchemy-eg6ch
@CsAlchemy-eg6ch 3 ай бұрын
Thanks
@ScottKFraley
@ScottKFraley 6 ай бұрын
So, `.so` works in Windows and isn't just a *nix thing? I always thought that it had to be `.dll` in/for Windows. (Course, for all I know, he may be running in some flavor of *nix. May have missed that part.)
@coderslegacy5661
@coderslegacy5661 6 ай бұрын
I'm running this on windows, so ig its a windows thing.
@ScottKFraley
@ScottKFraley 6 ай бұрын
@@coderslegacy5661 Wow, TIL.
@KingGisInDaHouse
@KingGisInDaHouse 6 ай бұрын
Mr Mackie Teaches Programming
@user-rf4vc7mt4d
@user-rf4vc7mt4d Жыл бұрын
okay
@2dapoint424
@2dapoint424 Жыл бұрын
How to read complete string in python? You are returning it in C but not reading in python!
@coderslegacy5661
@coderslegacy5661 Жыл бұрын
I have more than just one video on ctypes. Its a pretty vast topic, and even the 3-4 videos I have on it now do not do it full justice. At any rate, you will likely find the answer to your question here: kzfaq.info/get/bejne/eMmHp6aHxJnNoYE.html
@2dapoint424
@2dapoint424 Жыл бұрын
@@coderslegacy5661 Thank you. I did not find where you returned char* from C and python reading it. In my project I tried using str = cpp.TestString() print(str) #prints some number print(c_char_p(str)) # does not print anything print(c_char_p(str).value)) # crash in C the function is straight forward: char* TestString() { char* str = (char *) malloc(100); strcpy(str, "Hello"); return str; }
@coderslegacy5661
@coderslegacy5661 Жыл бұрын
@@2dapoint424 I see. It must have been in the other video then, about pointers. I understand your problem. What you need to do in your Python file, is this. cstring_pointer = alloc_func() str =ctypes.c_char_p.from_buffer(cstring_pointer) print(str.value) Here is a link to the article of mine from which I picked up this code. You can view the full thing there. coderslegacy.com/python/using-pointers-with-ctypes/
@2dapoint424
@2dapoint424 Жыл бұрын
@@coderslegacy5661 This was super helpful bro!!!!! Thank you so much, I had spent weeks in vain... Can I ask you one thing, any book you can recommend where I can learn more about all this please? your website is super helpful, am passing this to my school friends..
@coderslegacy5661
@coderslegacy5661 Жыл бұрын
@@2dapoint424 Glad to have been of help. I'm afraid I don't know about any book for ctypes. I've been learning it using the documentation page + going through other peoples code on stack overflow. I've realized that alot of people have trouble with ctypes, so I'm planning to release some more content on it. I have two video tutorials planned for this week.
@lonezombieheart7808
@lonezombieheart7808 9 ай бұрын
ok?
@IngRandall
@IngRandall Жыл бұрын
this video it´s only C not C++??
@coderslegacy5661
@coderslegacy5661 Жыл бұрын
I've talked about C++ specifically in this video here. kzfaq.info/get/bejne/mJd1YJd2v7Cdf4k.html There is an extra thing or two you need to do for C++ code, so I made a video dedicated to C++ with ctypes.
@IngRandall
@IngRandall Жыл бұрын
@@coderslegacy5661 thank you.
@maksimluzin1121
@maksimluzin1121 9 ай бұрын
Ok, ok, ok every five seconds! Pls, do not use the garbage words, it's annoying really! P.S. The video, by the way, was useful...
@tomnetoo
@tomnetoo 10 ай бұрын
(!better) i don't mean it works without problems
Python ctypes Library - Memory, Strings, Datatypes
16:47
CodersLegacy
Рет қаралды 8 М.
Using Structs and Classes with Python Ctypes
25:37
CodersLegacy
Рет қаралды 5 М.
路飞被小孩吓到了#海贼王#路飞
00:41
路飞与唐舞桐
Рет қаралды 77 МЛН
New model rc bird unboxing and testing
00:10
Ruhul Shorts
Рет қаралды 23 МЛН
Python C Extensions
21:59
Tobias Bergkvist
Рет қаралды 8 М.
Unlocking your CPU cores in Python (multiprocessing)
12:16
mCoding
Рет қаралды 297 М.
Premature Optimization
12:39
CodeAesthetic
Рет қаралды 774 М.
Compiled Python is FAST
12:57
Doug Mercer
Рет қаралды 102 М.
why do header files even exist?
10:53
Low Level Learning
Рет қаралды 379 М.
C++ in Python the Easy Way! #pybind11
9:57
Jack of Some
Рет қаралды 98 М.
Mastering Memory: Allocation Techniques in C, C++, and ARM Assembly
17:05