This time it's a pointer operation, so To use pointers in python, I could write code in Python without thinking about it. I haven't studied much, but I will describe what I have investigated.
After a lot of research, I found something called ctypes — external function library for Python. I was grateful to see this because the tutorial was in Japanese, but since it was a usage method on Windows, I was looking for various ways to use it on Mac stacoverflow 11554355 / mac-os-x-lion-python-ctype-cdll-error-lib-so-6-image-not-found).
I tried using it in my own environment, so I will describe it.
>>> from ctypes import *
>>> cdll.LoadLibrary("libc.dylib")
<CDLL 'libc.dylib', handle 7fff6903da98 at 0x1052f6fd0>
>>> libc = CDLL("libc.dylib")
>>> printf = libc.printf
>>> printf(b"Hello, %s\n", b"World!")
Hello, World!
14
>>> strchr = libc.strchr
>>> strchr(b"abcdef", ord("d"))
87110915
>>>
As an important issue
It was that, The following answer by manipulating the array C ++ code
void append(arrayString& s, char c){
int oldLength = 0;
while(s[oldLength] != 0) {
oldLength++;
}
arrayString newS = new char[oldLength + 2];
for(int i = 0; i < oldLength; i++) {
newS[i] = s[i];
}
newS[oldLength] = c;
newS[oldLength + 1] = 0;
delete[] s;
s = newS;
}
#!/usr/bin/env python
#coding:utf-8
#ctypes module(for mac)
from ctypes import *
#cdll.LoadLibrary("libc.dylib")
#libc = CDLL("libc.dylib")
def add(s,c):
print('Previous string:',list(s))
print('Previous pointer:', c_wchar_p(s))
newlength = len(s)+2
newS = []
for i in s:
newS += i
for j in c:
newS += j
print('After string:',newS)
print('After pointer:', c_wchar_p(str(newS)))
>>>(Execution terminal)
>>> from test38 import add
>>> add("test","! ")
Previous string:['t', 'e', 's', 't']
Previous pointer: c_wchar_p(140481723952464)
After string:['t', 'e', 's', 't', '!', ' ']
Pointer after: c_wchar_p(140481723970864)
>>>
I didn't really need the ctypes module, but I learned that Python can also use C.
Recommended Posts