'C, C++'에 해당되는 글 34건

  1. 2018.11.21 Python C API
  2. 2018.11.20 MySQL C API

Python C API

C, C++ 2018. 11. 21. 15:52 |
반응형

가장 간단하게 Python을 C에 embed 시키는 방법은 Very High Level interface를 사용 하는 것이다. VHL interface는 어플리케이션과 직접적인 상관 없이 Python script를 실행하기 위한 것이다.


관련 문서

Python/C API Reference Manual


우선 Python C API 관련 Include, Library 디렉토리를 프로젝트에 추가한다.


파이썬 공식 홈페이지에서 다운 받은 파이썬 인스톨러 패키지를 설치 했다면 Solution Configurations를 Release로 설정 한다. Debug 모드로 build 할 경우 pythonXX_d.lib를 찾을 수 없다는 에러가 발생한다. pythonXX_d.lib 파일을 생성하려면 파이썬 소스를 받아서 직접 컴파일해야 한다.


예제:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#pragma comment(lib, "python36.lib")
#include <Python.h>
 
int main(int argc, char *argv[])
{
    wchar_t *program = Py_DecodeLocale(argv[0], NULL);
    // Decode a byte string from the locale encoding with the surrogateescape error handler:
    // undecodable bytes are decoded as characters in range U+DC80..U+DCFF. If a byte sequence
    // can be decoded as a surrogate character, escape the bytes using the surrogateescape error
    // handler instead of decoding them.
    // Return a pointer to a newly allocated wide character string, use PyMem_RawFree() to free
    // the memory. If size is not NULL, write the number of wide characters excluding the null
    // character into *size
    if (program == NULL) {
        fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
        exit(1);
    }
    Py_SetProgramName(program);  /* optional but recommended */
    // This function should be called before Py_Initialize() is called for the first time, if it
    // is called at all.It tells the interpreter the value of the argv[0] argument to the main()
    // function of the program(converted to wide characters).This is used by Py_GetPath() and some
    // other functions below to find the Python run - time libraries relative to the interpreter
    // executable.
 
    Py_Initialize();
    // Initialize the Python interpreter. In an application embedding Python, this should be called
    // before using any other Python/C API functions
    if (Py_IsInitialized())
    // Return true (nonzero) when the Python interpreter has been initialized, false (zero) if not.
    // After Py_FinalizeEx() is called, this returns false until Py_Initialize() is called again.
    {
        PyRun_SimpleString("print('Hello Python')");
        // This is a simplified interface to PyRun_SimpleStringFlags(), leaving the PyCompilerFlags*
        // argument set to NULL.
        PyRun_SimpleString("from time import time, ctime\n"
            "print('Today is', ctime(time()))\n");
        //PyRun_SimpleString("from time import time, ctime\nprint('Today is', ctime(time()))\n");
 
        if (Py_FinalizeEx() < 0)
        // Undo all initializations made by Py_Initialize() and subsequent use of Python/C API
        // functions, and destroy all sub-interpreters that were created and not yet destroyed
        // since the last call to Py_Initialize().
        {
            exit(120);
        }
        PyMem_RawFree(program);
        // Frees the memory block pointed to by p, which must have been returned by a previous call
        // to PyMem_RawMalloc(), PyMem_RawRealloc() or PyMem_RawCalloc().
        // Otherwise, or if PyMem_RawFree(p) has been called before, undefined behavior occurs.
        // If p is NULL, no operation is performed.
    }
 
    return 0;
}
cs


반응형
Posted by J-sean
:

MySQL C API

C, C++ 2018. 11. 20. 11:31 |
반응형

MySQL C API 는 C 프로그램이 MySQL 데이터 베이스 내용에 접근 할 수 있도록 MySQL 서버/클라이언트 프로토콜의 저수준 접근을 제공 한다.

 

5.7 버전 참고 문서: MySQL C API

 

설정:

  • 버전 설정: X64

  • Project - XXX Properties... - Configuration Properties - C/C++ - General - Additional Include Directories - C:\Program Files\MySQL\MySQL Server 5.7\include 추가
  • Project - XXX Properties... - Configuration Properties - Linker - General - Additional Library Directories - C:\Program Files\MySQL\MySQL Server 5.7\lib 추가

 

 

  • Project - XXX Properties... - Configuration Properties - Linker - Input - Additional Dependencies - libmysql.lib 추가 하거나 소스에 아래 코드 추가
    #pragma comment (lib, "libmySQL.lib")
  • 실행파일 폴더에 libmysql.dll 복사

 

예제:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <my_global.h>
#include <mysql.h>
 
#pragma comment (lib, "libmySQL.lib")
 
int main()
{
    MYSQL mysql;            // MySQL 정보를 담을 구조체
    MYSQL* mysqlPtr = NULL;    // MySQL connection 핸들러
    MYSQL_RES* Result = NULL;        // 쿼리 성공시 결과를 담는 구조체 포인터
    MYSQL_ROW Row;            // 쿼리 성공시 결과로 나온 행의 정보를 담는 구조체
    int stat;                // 쿼리 요청 후 결과
 
    printf("MySQL Client Version: %s\n\n", mysql_get_client_info());
    // Returns client version information as a string
 
    mysql_init(&mysql); // Gets or initializes a MYSQL structure 
 
    mysqlPtr = mysql_real_connect(&mysql, "127.0.0.1""root""1234""shopdb"3306, (char*)NULL0);
    // Connects to a MySQL server
 
    if (mysqlPtr == NULL)
    {
        printf("MySQL connection error: %s\n", mysql_error(&mysql));
        // Returns the error message for the most recently invoked MySQL function
        return 1;
    }
 
    // MySQL에서 사용하는 문자세트를 Visual Studio가 사용하는 euc-kr로 바꾸기
    mysql_query(mysqlPtr, "set session character_set_connection=euckr");
    mysql_query(mysqlPtr, "set session character_set_results=euckr");
    mysql_query(mysqlPtr, "set session character_set_client=euckr");
 
    const char* Query = "SELECT * FROM memberTBL";
    stat = mysql_query(mysqlPtr, Query);    // Executes an SQLquery specified as a null-terminated string
    if (stat != 0)
    {
        printf("MySQL connection error: %s\n", mysql_error(&mysql));
        return 1;
    }
 
    Result = mysql_store_result(mysqlPtr);    // Retrieves a complete result set to the client
    while ((Row = mysql_fetch_row(Result)) != NULL)    // Fetches the next row from the result set 
    {
        printf("%s %s %s\n", Row[0], Row[1], Row[2]);
    }
 
    mysql_free_result(Result);    // Frees memory used by a result set
    mysql_close(mysqlPtr);    // Closes a server connection
 
    return 0;
}
cs

5.7 버전의 MySQL은 빌드하면 C2011('struct' type redefinition) 에러가 발생하는 경우가 있다.

C2011 에러가 발생 하면 my_global.h 파일에 #define HAVE_STRUCT_TIMESPEC 코드를 추가해 준다.

 

 

반응형
Posted by J-sean
: