简体   繁体   中英

Calling a C library method from swift using pointers

Given the following ODBC C API information and associated type definitions, how does one call the SQLSetEnvAttr function from swift ?

From swift , my code successfully invokes the prerequisite SQLAllocHandle function which provides the handle to the environment ( henv ) utilized in the subsequent SQLSetEnvAttr function call.
I have tried a variety of approaches including UnsafeMutablePointer , attempting to follow instructions referenced on the following sites, but I couldn't figure out how to get the compiler to allow me to convert from a Void * to a SQLPOINTER (even though it is defined to be the same thing). Additionally, I was stymied on how to make the UnsafeMutablePointer point to the value of the CUnsignedLong variable ( SQL_OV_ODBC3 typedef) I used (set to 3 )

ODBC API

typedef signed short int SQLSMALLINT;
typedef SQLSMALLINT     SQLRETURN;
typedef void *          SQLPOINTER;
#define SQL_ATTR_ODBC_VERSION               200
#define SQL_OV_ODBC3                        3UL

retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION,
             (SQLPOINTER) SQL_OV_ODBC3, 0);

The working swift code that gets me the handle to the environment is:

var sqlHenvPtr : UnsafeMutablePointer<SQLHENV> = UnsafeMutablePointer<SQLHENV>.alloc(1) var retcode : CShort = SQLAllocHandle(Int16(SQL_HANDLE_ENV), nil, sqlHenvPtr)

Looking for help with how to define and pass the third parameter:

let SQL_ATTR_ODBC_VERSION : Int32 = 200
retcode = SQLSetEnvAttr(sqlHenvPtr.memory, SQL_ATTR_ODBC_VERSION, ???, 0)

Any assistance would be much appreciated.

Updated per Chris's feedback

let value = UnsafeMutablePointer<Void>(bitPattern: 3)
SQLSetEnvAttr(0, 0, value, 0)

The expected value by SQLSetEnvAttr() is 0x3 (in your case it was 0x10025a478 ). I verified that my own prototype C function which accepts SQLPOINTER receives 0x3 in case of preparing 3rd parameter in proposed way. Hope it helps now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM