2012년 12월 2일 일요일

ctypeslib 를 mingw 와 같이 쓰기.

2008년도에 파이썬마을 강좌란(http://python.kr/viewtopic.php?t=23655) 써 놓은 글인데 한동안 파이썬마을이 불안정했던 적이 있어서 백업차원에서 여기에 다시 정리.
----------------------------------------------------------
윈도환경에서 ctypes 를 가끔 쓰고 있는데 WIN32 API 를 일일히 기술하려니 짜증~~
그래서, ctypes 홈페이지를 보니 역시 ctypeslib 라는 자동화툴이 있더군요.

문제는 ctypes 홈페이지에 있는 gccxml 윈도용 설치파일이 mingw(정확히는 g++)를 지원하지 않습니다.
CVS 에 있는 gccxml 은 mingw 를 지원하는데 윈도용 설치파일은 따로 없더군요.
그래서, 삽질을 시작했습니다.

0. 작업환경
Windows 7 SP1 64bit, Python 2.7.3 32bit


1. mingw 설치하기.
gccxml 빌드시, ctypeslib 사용시에 mingw 가 필요함. 

mingw(http://www.mingw.org/) 또는 tdm-gcc(http://tdm-gcc.tdragon.net/) 설치.
여기서는 tdm-gcc 사용.
PATH 환경변수에 mingw 의 bin 폴더를 추가함.

2. CMake 설치. 

cmake(http://www.cmake.org/) 를 설치.
PATH 환경변수에 cmake 의 bin 폴더를 추가.

3. gccxml 소스 체크아웃.
http://gccxml.org/HTML/Index.html 를 참고하여 gccxml 소스 체크아웃함.
(여기서는 d:\prj\gccxml\gccmxl 에 체크아웃)

D:\prj\gccxml\gccxml>dir
 D 드라이브의 볼륨: 새 볼륨
 볼륨 일련 번호: 7C0A-AD6D

 D:\prj\gccxml\gccxml 디렉터리

2008-03-19  19:47    (DIR)          .
2008-03-19  19:47    (DIR)          ..
2008-02-15  09:50             1,114 CMakeLists.txt
2008-03-19  19:47    (DIR)          GCC
2007-11-01  00:57             2,688 gccxmlCPack.cmake
2008-03-19  19:47    (DIR)          GCC_XML
2007-11-29  04:52             2,312 README
               3개 파일               6,114 바이트
               4개 디렉터리  66,559,102,976 바이트 남음

D:\prj\gccxml\gccxml>


4. CMake 로 gccxml 빌드환경 설정.
cmake-gui.exe 실행.
Where is the source code : 소스폴더지정(여기서는 d:\prj\gccxml\gccxml)
Where is the binaries : 빌드된 바이너리 저장폴더 지정.(여기서는 d:\prj\gccxml\build 폴더 만들고 지정)

Configure 버튼 누름.
Mingw Makefiles 항목 선택.

정상적으로 되었으면 CMAKE_BUILD_TYPE, CMAKE_INSTALL_PREFIX 항목 보임.
CMAKE_BUILD_TYPE 항목 : Release 라고 타이핑.
CMAKE_INSTALL_PREFIX : 어떤 항목인지 모름. 여기서는 c:\devtool\gccxml 폴더 만들고 지정. (최종적으로 여기에 설치됨)

다시, Configure 버튼 누름.
Generate 버튼 누름.

5. gccxml 빌드
명령행에서 build 폴더( 여기서는 d:\prj\gccxml\build ) 로 이동
mingw32-make 실행.
mingw32-make install 실행.

정상적이면 빌드폴더의 bin 폴더( 여기서는 c:\devtool\gccxml\build\bin ) 에 gccxml.exe 생성됨.

bin 폴더를 PATH 환경변수에 추가함.
(주의 : mingw\bin 폴더가 gccxml\bin 폴더보다 앞에 있어야 함
즉. set PATH=c:\devtool\mingw\bin;c:\devtool\gccxml\bin;%PATH% )
GCCXML_COMPILER 환경변수를 새로 만들고 g++ 이라고 입력함.
(만약, msvc를 사용할려면 msvc6,msvc7,msvc9.. 등으로 설정. 테스트해보지 않음
자세한 것은 doc 폴더(여기서는 c:\devtool\gccxml\build\GCC_XML\doc) 문서 참조.)

6. ctypeslib 체크아웃 및 설치.
ctypeslib(http://pypi.python.org/pypi/ctypeslib 또는 http://starship.python.net/crew/theller/ctypes/)에서 소스를 체크아웃후 설치.

7. ctypeslib 사용
ctypeslib 문서를 참조하여 다음과 같은 파이썬 코드 실행.

2012년 11월 20일 화요일

mingw 로 qrencode dll 빌드



http://fukuchi.org/works/qrencode/index.html.en

./configure
make
make install

qrencode 를 mingw + msys 로 dll 빌드시 계속 static 라이브러리만 생성됨.
ubuntu 에서는 정상적으로 so 파일 생성.

구글링해보니 약간의 패치가 옵션조정이 필요함.
pthread 라이브러리 링크에 문제가 있는 것으로 보임.
pthread  static 라이브러를 링크해볼려고 했으나 mingw 의 pthread static 라이브러리에 문제가 있는 것 같음.

http://lrn.no-ip.info/other/mingw/mingw32/qrencode/3.3.1-2/

Makefile.in 에서 다음줄을 찾아서  -no-undefined 추가.
libqrencode_la_LDFLAGS = -version-number $(MAJOR_VERSION):$(MINOR_VERSION):$(MICRO_VERSION)
libqrencode_la_LDFLAGS = -version-number $(MAJOR_VERSION):$(MINOR_VERSION):$(MICRO_VERSION) -no-undefined
다시 빌드.
make clean
./configure --without-tools --disable-thread-safety
make
mae install
./libs 폴더에 dll 이 생성된 것을 볼 수가 있음.
thread safe 하지 않으므로 lock 은 알아서 잘 해야 될 것 같음.

2012년 10월 19일 금요일

Trac wikiprint 한글글꼴 설정.

아래 링크를 참조하여 한글이 포함된 trac 페이지도 wikiprint 로 PDF 문서를 잘 생성해서 쓰고 있었는데 어느때인가? ubuntu 를 업그레이드하면서 한글이 깨지기 시작했다.
http://kldp.org/node/109178

오늘 ubuntu 12.10 으로 업그레이드하면서 다시 확인해봤는데 역시나~~
이것저것 삽질하다 보니 짜안 한글이 TT_TT..
/usr/share/pyshared/wikipiprint/defaults.py 를 아래와 같이 수정.
  • 원본..
"""
Author: Alvaro Iradier
"""

#Default CSS to use for xhtml2pdf
CSS = """
html {
    font-family: Helvetica;
    font-size: 10px;
    font-weight: normal;
    color: #000000;
    background-color: transparent;
  • 수정본
"""
Author: Alvaro Iradier
"""

#Default CSS to use for xhtml2pdf
CSS = """
@font-face {
    font-family: NanumGothic;
    src: url(file:///usr/share/fonts/truetype/nanum/NanumGothic.ttf);
    }
html {
    font-family: NanumGothic;
    font-size: 10px;
    font-weight: normal;
    color: #000000;
    background-color: transparent;

2012년 10월 18일 목요일

리눅스배포판 정보 얻기

$ lsb_release -rd
Description:    Ubuntu 12.10
Release:    12.10

파이썬에서 r"\x30" 디코딩하기.


>>> r"\x30".decode("string_escape")
'0'

2012년 3월 7일 수요일

gcc 에서 디버깅심볼을 별도 파일로 저장하기.

http://stackoverflow.com/questions/866721/how-to-generate-gcc-debug-symbol-outside-the-build-target

분리할 때..
gcc -ggdb -o test test.c;
cp test test.debug;
strip --only-keep-debug test.debug;
strip test;


합칠 때
objcopy --add-gnu-debuglink=test.debug test


gdb 에서..
http://sigquit.wordpress.com/2008/09/15/debugging-programs-with-a-external-symbol-file/
(gdb) symbol-file test.debug

2012년 2월 9일 목요일

라자루스에서 TForm 생성시 class name 바꾸기..

아래링크를 참조하여 윈도용 라자루스에서 TForm 의 Class Name 을 바꿔보려 했다.
http://cbuilder.borlandforum.com/impboard/impboard.dll?action=read&db=bcb_tip&no=1072
라자루스에서 TForm 의 기본 class name 은 'Window' 인데 아래와 같이 해도 바뀌지는 않는다.

type
{ TFormMain }
TFormMain = class(TForm)
....
protected
PrevWndProc: Windows.WNDPROC;
procedure WndProc( var TheMessage: TLMessage); override;
procedure CreateParams(var Params: TCreateParams); override;
end;

procedure TFormMain.CreateParams(var Params: TCreateParams);
begin
inherited;
StrCopy(Params.WinClassName, 'MyClass');
end;

procedure TFormMain.MenuItem2Click(Sender: TObject);
var
class_name :array [0..255] of Char;
ret :LongInt;
begin
ret := GetClassName(WindowHandle, class_name, SizeOf(class_name));
if ret > 0 then
begin
MessageDlg(class_name, mtInformation, [mbOK], 0 )
end;
end;
그래서, 라자루스 포럼에 질문을 올렸더니, 직접 패치를 만들어보라는 대답이 돌아왔다. TT_TT;;
http://www.lazarus.freepascal.org/index.php/topic,15941.msg86071.html#msg86071
그래서, 직접 수정해보기로 했다.
라자루스 소스를 분석해보면 TCreateParams.WinClassName 를 전혀 사용하지 않고 있다.
아래 코드와 같이 대충 동작하도록 만들어보았는데, 윈7, XP 에서 동작하는 것을 확인했다.
Ansi 쪽이 호출되는 상황이면 충돌이 발생하는데 그 원인을 모르겠다.
파스칼,델파이,라자루스 모두 익숙하지 않은지라 그리 깔끔해보지는 않는다.
고수님들이 손 봐줬으면 좋겠다.
Lazarus-0.9.31-35255-fpc-2.6.1-20120209-win32.exe 에 포함된 소스를 기준으로 작업

unit Win32WSForms;

{$mode objfpc}{$H+}
{$I win32defines.inc} // added

interface
....
....
class function TWin32WSCustomForm.CreateHandle(const AWinControl: TWinControl;
const AParams: TCreateParams): HWND;
var
Params: TCreateWindowExParams;
lForm: TCustomForm absolute AWinControl;
Bounds: TRect;
SystemMenu: HMenu;
// addtion start
WindowClass: WndClass;
{$ifdef WindowsUnicodeSupport}
WindowClassW: WndClassW;
{$endif}
AErrorCode: Cardinal;
// addtion end
begin
// general initialization of Params
PrepareCreateWindow(AWinControl, AParams, Params);
// customization of Params
with Params do
begin
if (Parent = 0) then
begin
 ......
end;
CalcFormWindowFlags(lForm, Flags, FlagsEx);
pClassName := @ClsName[0];

// addtion start
if AParams.WinClassName[0] <> #0 then
begin
pClassName := @AParams.WinClassName[0];
{$ifdef WindowsUnicodeSupport}
if UnicodeEnabledOS then
begin
  if not GetClassInfoW(System.HInstance(), PWideChar(WideString(pClassName)), @WindowClassW) then
  begin
    if GetClassInfoW(System.HInstance(), PWideChar(WideString(ClsName)), @WindowClassW) then
    begin
  WindowClassW.lpszClassName:=PWideChar(WideString(pClassName));
  if Windows.RegisterClassW(@WindowClassW) = 0 then
  begin
    AErrorCode := GetLastError;
    //DebugLn(['Failed to RegisterClassW, error: ', AErrorCode, ' : ', GetLastErrorText(AErrorCode)]);
    raise Exception.Create('Failed to RegisterClassW, error: ' + IntToStr(AErrorCode) + ' : ' + GetLastErrorText(AErrorCode));
  end;
    end
    else
    begin
      AErrorCode := GetLastError;
  //DebugLn(['Failed to GetClassInfoW, error: ', AErrorCode, ' : ', GetLastErrorText(AErrorCode)]);
  raise Exception.Create('Failed to GetClassInfoW, error: ' + IntToStr(AErrorCode) + ' : ' + GetLastErrorText(AErrorCode));
    end;
  end;
end
else
{$endif}
begin
  FillChar(WindowClass, SizeOf(WindowClass),0);
  if not GetClassInfo(System.HInstance(), pClassName, @WindowClass) then
  begin
    if GetClassInfo(System.HInstance(), PChar(AnsiString(ClsName)), @WindowClass) then
    begin
  WindowClass.lpszClassName:=pClassName;
  if Windows.RegisterClass(@WindowClass) = 0 then
  begin
    AErrorCode := GetLastError;
    //DebugLn(['Failed to RegisterClass, error: ', AErrorCode, ' : ', GetLastErrorText(AErrorCode)]);
    raise Exception.Create('Failed to RegisterClass, error: ' + IntToStr(AErrorCode) + ' : ' + GetLastErrorText(AErrorCode));
  end;
    end
    else
    begin
      AErrorCode := GetLastError;
  //DebugLn(['Failed to GetClassInfo, error: ', AErrorCode, ' : ', GetLastErrorText(AErrorCode)]);
  raise Exception.Create('Failed to GetClassInfo, error: ' + IntToStr(AErrorCode) + ' : ' + GetLastErrorText(AErrorCode));
    end;
  end;
end;
end;
// addtion end

WindowTitle := StrCaption;
AdjustFormBounds(lForm, Bounds);
if (lForm.Position in [poDefault, poDefaultPosOnly]) and not (csDesigning in lForm.ComponentState) then
begin
....