Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Missing example with string in key/value #1

Open
recoilme opened this issue Nov 4, 2016 · 0 comments
Open

Missing example with string in key/value #1

recoilme opened this issue Nov 4, 2016 · 0 comments

Comments

@recoilme
Copy link

recoilme commented Nov 4, 2016

Hi
I try implement string key/value storage and found this to hard for me
If i right understand - sophia not store strings as cstring, but as array of bytes
If i right code in errorExit - will not work, (cast to cstring in Nim will fail with segfault)

I found the strange workarround how set string and get it with casting to array[0,char]
It's work, but i dont understand why) May you explain how do it right?

My code is:


import sophia,strutils

proc free(obj: pointer) {.importc: "free", header: "<stdio.h>"}

proc errorExit() =
  var size: cint
  var error = env.getstring("sophia.error", addr size);
  #cast to csting not working?
  var msg = $(cast[ptr cstring](error)[])
  echo("Error: " & msg)
  free(error)
  discard env.destroy()

# Create a Sophia environment
var env = env()

# Set directory and add a db named test
discard env.setstring("sophia.path", "sophia3".cstring, 0)
discard env.setstring("db", "db".cstring, 0)

# Get the db
var db = env.getobject("db.db")

# Open the environment
var rc = env.open()
if (rc == -1):  errorExit()
echo "Opened Sophia env"

# Store strings
var o:pointer
var key:string = "hello"
var value:string = "hello world"

o = document(db)
discard o.setstring("key".cstring, addr key[0], (key.len).cint)
discard o.setstring("value".cstring, addr value[0], (value.len).cint)
rc =  db.set(o);
if (rc == -1): errorExit()
o = document(db)
discard o.setstring("key".cstring, addr key[0], (key.len).cint)
o = db.get(o)
if (o!=nil):
  var valPointer = o.getstring("value".cstring, nil)
  #very strange but work
  var returnVal = $(cast[ptr array[0,char]](valPointer)[])
  echo returnVal
  echo returnVal.len
else: 
  echo "not found"  
echo "Yup, it's gone, all good"

# Clean up
discard destroy(env)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant