Hi, everyone, i am a Python programmer and found use nimpy write python extention is super easy than Go,Rust, then i am try to write the code below:
import nimpy
import nimAES
proc encrypt(n string): string {.exportpy.} =
var ctx: AESContext
zeroMem(addr(ctx), sizeof(ctx))
var key = "0123456789ABCDEF"
if ctx:setEncodeKey(key):
var out1 = newString(len(n))
var output1 = cstring(out1)
ctx.encryptECB(cstring(n), output1)
return $output1
then compile the file pwgen.nim with
nim c -d:release --app:lib --gc:regions --out:pwgen.so pwgen.nim
and using in python
from pwgen import encrypt
secret = "hello, world"
print(encrypt(secret))
which output is byte and got decode error when turn it into string
Any advice are appreciate.
Nimpy encodes your string to a sequence of bytes using utf-8 (in proc pyStringToNim). When returning $output1, nimpy needs to do the inverse of this encoding step. The error is probably raised because the encrypted data is not valid utf-8, which causes the decoding to throw an exception.
My suggestion would be to change your function to use a return type that maps to a python bytes object. (bytes is the recommended type for storing binary data in python3.)
Like @meep said, your encrypt function returns an invalid utf-8 sequence, which nimpy silently converts to python bytes as a fallback.
Question is what are you expecting to get on the python side? If string, what should it look like? If array, array of what?
Btw, if you need a string with the hex representation, just use return toHex($outpu1) and import strutils.
I would suggest that binary data is represented as bytes in python, which is what you're getting.