Hello
I made some experiences connecting Nim with Python. At this page
[http://akehrer.github.io/posts/connecting-nim-to-python](http://forum.nim-lang.org///akehrer.github.io/posts/connecting-nim-to-python)/
there are some cool hints about how to do that. However, I got some issues
interfacing with string types.
How can I declare a string at Nim and how should I treat it in Python ?
I have the following code in Nim ('nim2py.nim)':
proc AmericanSoundexCode(ch: char): int =
case ch:
of 'B', 'F', 'P', 'V' : return 1
of 'C', 'G', 'J', 'K', 'Q', 'S', 'X', 'Z' : return 2
of 'D', 'T' : return 3
of 'L' : return 4
of 'M', 'N' : return 5
of 'R' : return 6
of 'A', 'E', 'I', 'O', 'U', 'Y' : return -1
else : return 0
proc AmericanSoundex*(word: string): string {. exportc, dynlib .} =
var output = newString(4)
var lastCode = 0
var i, j = 0
# Get the first character
while i < word.len:
var ch = word[i]
inc i
# Reduce a lowercase character to an uppercase character
if ((ch.int >= 97) and (ch.int <= 122)): dec ch, 32
if ((ch.int >= 65) and (ch.int <= 90)):
lastCode = AmericanSoundexCode(ch)
if lastCode < 0: lastCode = 0
output[j] = ch
inc j
break
# Now lets hash the rest of this stuff
while i < word.len:
var ch = word[i]
inc i
# Reduce a lowercase character to an uppercase character
if ((ch.int >= 97) and (ch.int <= 122)): dec ch, 32
if ((ch.int >= 65) and (ch.int <= 90)):
var code = AmericanSoundexCode(ch)
case code:
of 0: continue
of -1:
lastCode = 0
else:
if code != lastCode:
lastCode = code
output[j] = char(code + 48)
inc j
if j == 4: break
# Pad the remainder of the string with zeroes
while j < 4:
output[j] = '0'
inc j
# We are done
return output
In Python I'm doing the following:
from ctypes import *
def main():
test_lib = CDLL('nim2py')
...
mystring = "robert james fischer"
soundex_res = test_lib.AmericanSoundex(mystring)
print('The Soundex is: %s'%soundex_res)
if __name__ == '__main__':
main()
Here's the output I'm getting:
Traceback (most recent call last):
File "py_calling_nim.py", line 33, in <module>
main()
File "py_calling_nim.py", line 29, in main
soundex_res = test_lib.AmericanSoundex(mystring)
ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type
After converting the mystring to bytes I’m getting:
The Soundex is: b'x04'
Sorry, but I’m not sure where to go next other...