I tried your code and it turned out that mystring wasn't passed correctly to
the Nim proc. So I changed the type to cstring and added some test output
prints. In the Python code you have to create a string buffer.
So this works for me:
proc AmericanSoundex*(word: cstring): cstring {. exportc, dynlib .} =
var output = newString(4)
var lastCode = 0
var i, j = 0
echo "Nim-Input: ", word
# 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
echo "Nim-Output: ", output
return output
from ctypes import *
def main():
test_lib = CDLL('./libAmSoundex.so')
test_lib.AmericanSoundex.argtype = c_char_p
test_lib.AmericanSoundex.restype = c_char_p
p_input = create_string_buffer(b"robert james fischer", 25)
soundex_res = test_lib.AmericanSoundex(p_input)
print('The Soundex is:', soundex_res)
if __name__ == '__main__':
main()
giving me the following output:
Nim-Input: robert james fischer Nim-Output: R163 The Soundex is: b'R163'