Sign in Join
Wiki copytemporary

Creating bindings for C libraries/zh CN: what changed

Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11# 简介
22
33本页介绍了如何为“C语言库”创建“Pascal绑定”项目。为了在Pascal中使用C语言库,需要为每个C函数、类型和变量创建Pascal转译代码。这可以用h2pas之类的自动化工具来实现,或者对头文件进行人工转换。
44
55# H2PAS
66
77## 概述
88
99[[H2Pas]]工具可以对很多常见C语言元素进行自动转译。Lazarus提供了图形用户界面(GUI),可用h2pas和其他工具将创建过程自动化。这会创建一个用于更新绑定项目的规则集。这样后续版本的C库转换起来将会更加容易。h2pas向导程序的一个好特性就是使用临时文件,这样C语言头文件就能保持不变。
1010
1111## 工作步骤
1212
1313 * 获取需要转译的C语言头文件。
1414 * 创建工作目录并命名绑定项目。
1515 * 用向导程序新建h2pas项目。
1616 * 将.h文件加入项目。
1717 * 配置h2pas参数。
1818 * 运行向导程序。
1919 * 用文本添加工具修正错误,再次运行向导。
2020 * 如果h2pas运行没有错误了,尝试编译并加入其它工具以美化输出结果。
2121 * 编写测试程序对绑定项目进行测试。
2222 * 在lazarus-ccr或者FreePascal发布绑定项目。
2323
2424## 安装工具
2525
2626正常安装fpc都会自带h2pas工具。
2727
2828在Lazarus IDE中安装h2paswizard软件包。打开“软件包->安装/卸载软件包”,从右侧列表选中H2PasWizard 并点击“安装选中的”,然后点击“保存并重新构建IDE”。 重启IDE,就会出现新的菜单项:工具 -> h2pas。
2929
3030## 获取C语言头文件
3131
3232C语言.h头文件描述了C程序库的接口,通常不会和C程序库一起提供。必须得有源代码或者程序库的开发包才行。例如gtk库的头文件就在gtk+-devel包中。
3333
3434### 示例:MPICH2
3535
3636从http://www-unix.mcs.anl.gov/mpi/mpich2/下载mpich2-1.0.3.tar.gz并解压。.h文件都在mpich2-1.0.3/src/include下。 关于FPC的MPICH,更多信息请参阅[[MPICH|here]]。
3737
3838## 创建工作目录并命名绑定项目
3939
4040请用有意义的名字创建一个目录。目录名不能包含特殊字符,如空格、变音字符、句点和逗号。 将.h文件拷入目录。
4141
4242### 示例:MPICH2
4343
4444Pascal文件将存放于h2p目录。 .h文件将存放于h2p/c_sources目录。
4545```
4646mkdir -p h2p/c_sources
4747 cp mpich2-1.0.3/src/include/*.h h2p/c_sources/
4848```
4949
5050## 用h2pas向导程序新建h2pas项目
5151
5252从“工具 -> h2pas”打开向导程序。这会打开一个窗口。可以和其他IDE窗口之间来回切换。最近的2pas项目会自动加载。如要新建一个项目,请点击“设置 -> 新建/清除设置”。然后点击底部的“保存设置”按钮,选取文件名。
5353
5454注意:如果是第一次使用h2pas向导程序,需用“设置”页确认h2pas.exe转换程序的位置。转换程序h2pas.exe位于FreePascal编译器fpc.exe所在的目录中,如果连同Lazarus下载了FPC,则会位于...\Lazarus\fpc\_version_ \bin目录。请保存设置,下次就不必再设置了。
5555
5656### 示例:MPICH2
5757
5858请点击“设置 -> 新建/清除设置”。然后点击底部的“保存设置”按钮,保存为h2p/mpi2.h2p。
5959
6060## 在h2pas项目中添加.h文件
6161
6262在“C 语言头文件”页可以添加/删除.h文件。可以启用/禁用某些.h文件,以便只转换部分文件。
6363
6464### 示例:MPICH2
6565
6666点击“C 语言头文件 -> 添加 .h 文件 ...”,并选取“mpi.h”和“mpio.h”文件。他们会自动启用。选中mpi.h并点击“合并除此以外的所有内容”,这样向导程序就会将所有头文件并入一个单元文件(mpi.pas)
6767
6868## 设置h2pas参数
6969
7070在“H2Pas 选项”页,可以设置h2pas程序的参数。
7171
7272### 示例:MPICH2
7373
7474 * 启用-e、-D、-p、-w,并禁用其他所有选项。
7575 * -l 库名称路径设为“mpich”。
7676 * 输出扩展名为“.pas”。
7777 * 输出目录默认是h2pas/,所以保持为空即可。
7878
7979## 运行向导程序
8080
8181点击底部的“运行H2Pas”按钮。 这会将<example>.h文件拷贝成临时文件<example>.tmp.h,并运行“H2Pas 之前”页列出的工具。然后会运行h2pas将<example>.tmp.h转换为<example>.inc或<example>.pas,或者别的什么在“设置”页设置的输出扩展名。然后对输出文件运行“H2Pas 之后”页列出的工具。
8282
8383如果h2pas发现语法错误,将会用IDE打开example.tmp.h文件,并跳转到出错的行。通常h2pas只会报“syntax error”,非常宽泛。请参阅[[Common problems when converting C header files|转换C语言头文件时的常见问题]]。
8484
8585### 示例:MPICH2
8686
8787h2pas向导程序已包含的工具足以转换该头文件的所有内容,因此这里不会报错。但单元文件还没创建好,请继续。
8888
8989请切换到“H2Pas 之后”页,加入“Reduce compiler directives in pascal file”工具。
9090
9191在 _Undefines_ 属性中加入:
9292```
9393MPI_INCLUDED
9494 MPIO_INCLUDE
9595 NEEDS_MPI_FINT
9696 MPI_BUILD_PROFILING
9797 MPICH_SUPPRESS_PROTOTYPES
9898 MPI_Wtime
9999 HAVE_MPICH2G2
100100 FOO
101101 HAVE_PRAGMA_HP_SEC_DEF
102102```
103103
104104
105105在 _Defines_ 属性中加入:
106106```
107107MPICH2
108108 MPICH_NEW_MPIIO
109109```
110110
111111## 自行选用转换程序中的工具
112112
113113### 使用“搜索和替换”工具
114114
115115很多类似修改变量名之类的活儿都能用**搜索和替换** 工具完成。这通过“H2Pas 之前”或“H2Pas 之后”页中的'添加新工具'按钮就能加入。 然后设置**SearchFor** 、**ReplaceWith** 、 **Options** 和**Caption** 属性即可。
116116
117117#### trtRegExpr选项
118118
119119如果**Options** 中的trtRegExpr设为**True** ,则表示要使用[[IDE regular expressions|正则表达式]]。这样就能利用**元字符** 和**限定符** 对源代码进行复杂的调整和美化。[[IDE regular expressions]]中给出了**元字符** 和**限定符** 的清单及示例。
120120
121121### 示例:将标识符Tguint更名为guint
122122
123123属性 | 值
124124---|---
125125Caption | Rename Tguint to guint
126126SearchFor | Tguint
127127ReplaceWith | guint
128128Options | [trtMatchCase,trtWholeWord]
129129
130130### 示例:为多个标识符更名
131131
132132Tguint更名为guint,Tgulong更名为gulong,Tgint更名为gint:
133133
134134属性 | 值
135135---|---
136136Caption | Rename Tguint to guint
137-SearchFor |
138-```
139-T(guint|gint|gulong)
140-```
141-
137+SearchFor | T(guint|gint|gulong)
142138ReplaceWith | $1
143139Options | [trtMatchCase,trtWholeWord,trtRegExpr]
144140
145141### 示例:MPICH2
146142
147143#### 删除MPI_DUP_FN宏
148144
149145_MPI_DUP_FN_ 在mpi头文件中定义了两次。前一次是个空的宏定义,后一次是个实际函数。因此,第一次的定义应该删除。
150146
151147在“H2Pas 之前”加入**搜索和替换** 工具(加到最后),并设置如下:
152148
153149属性 | 值
154150---|---
155151Caption | Remove dummy define MPI_DUP_FN
156152Name | RemoveDummyDefineMPI_DUP_FN
157-SearchFor |
158-```
159-^#define\s+MPI_DUP_FN\s+MPIR_Dup_fn
160-```
161-
153+SearchFor | ^#define\s+MPI_DUP_FN\s+MPIR_Dup_fn
162154ReplaceWith |
163155Options | [trtMatchCase,trtRegExpr]
164156
165157#### 删除针对MPI_DUP_FN的类型转换
166158
167159在“H2Pas 之前”加入**搜索和替换** 工具(加到最后),并设置如下:
168160
169161属性 | 值
170162---|---
171163Caption | Remove MPI_DUP_FN Makros
172164Name | Remove_MPI_DUP_Func
173-SearchFor |
174-```
175-^#define .*MPI_DUP_FN\).*$
176-```
177-
165+SearchFor | ^#define .*MPI_DUP_FN\\).*$
178166ReplaceWith |
179167Options | [trtMatchCase,trtRegExpr]
180168
181169#### 删除 MPIO_Test、PMPIO_Test、MPIO_Wait 和 PMPIO_Wait 函数
182170
183171MPIO_Test、PMPIO_Test、MPIO_Wait和PMPIO_Wait都定义了两次,同时定义了宏。因此函数定义应该删除:
184172
185173在“H2Pas 之前”加入**搜索和替换** 工具(加到最后),并设置如下:
186174
187175属性 | 值
188176---|---
189-Caption |
190-```
191-Remove Func P?MPIO_(Test|Wait)
192-```
193-
177+Caption | Remove Func P?MPIO_(Test|Wait)
194178Name | RemoveFuncP_MPIO_Test_Wait
195-SearchFor |
196-```
197-^int P?MPIO_(Test|Wait).*$
198-```
199-
179+SearchFor | ^int P?MPIO_(Test|Wait).*$
200180ReplaceWith |
201181Options | [trtMatchCase,trtRegExpr]
202182
203183## 改进已有转换工具
204184
205185发现缺陷后想要修复,或者扩展上述工具。很好!
206186
207187大部分转换工具的代码都在 h2paswizard 包的 h2pasconvert 单元中。 转换工具程序至少需要类名、说明和**Execute** 方法。 若要脱离 IDE 调试代码并节省大量的编译时间,请参阅项目 components/simpleideintf/examples/testh2pastool.lpi。 请编译后在控制台/终端中启动,并将 .h 文件名作为第一个命令行参数。例如:
208188```
209189./testh2pastool files/h2pastest.pas
210190```
211191
212192## 编写自定义转换工具
213193
214194自行编写转换工具并在 IDE 中注册,也都很容易。 启动一个软件包并加入新的单元文件(比如 unit1),定义一个类。已有工具的代码可以作为示例,请参阅前文。 新的转换工具编写完成并用上述 simpleideintf 项目测试通过后,即可在 IDE 中注册了: 在单元文件(unit1)中添加 **register** 过程,类似以下代码(伪代码):
215195```
216196uses
217197 Classes, ..., IDETextConverter;
218198
219199 type
220200 TYourToolClass = class(TCustomTextConverterTool)
221201 public
222202 class function ClassDescription: string; override;
223203 function Execute(aText: TIDETextConverter): TModalResult; override;
224204 end;
225205
226206 procedure Register;
227207
228208 implementation
229209
230210 procedure Register;
231211 begin
232212 TextConverterToolClasses.RegisterClass(TYourToolClass);
233213 end;
234214```
235215
236216别忘了在软件包编辑器中为对应单元勾选 **register** ,否则 IDE 不会去调用 Register 过程。 然后在 IDE 中安装此软件包。
237217
238218## 未来任务/未尽事宜
239219
240220 * 将静态链接函数转换为动态链接函数变量的工具
241221 * 修正参数名缺失函数的工具,可通过检索 .c 文件完成修复。还可加入注释,注明找到对应函数的 c 文件名。
242222 * 查到缺失的标识符,并让用户确认是否要注释掉或用基础类型取而代之。
243223 * 建立一份已完成部分转译的宏清单。
244224
245225C:
246226```
247227typedef struct page
248228 {
249229 u32int present : 1; // Page present in memory
250230 u32int rw : 1; // Read-only if clear, readwrite if set
251231 u32int user : 1; // Supervisor level only if clear
252232 u32int accessed : 1; // Has the page been accessed since last refresh?
253233 u32int dirty : 1; // Has the page been written to since last refresh?
254234 u32int unused : 7; // Amalgamation of unused and reserved bits
255235 u32int frame : 20; // Frame address (shifted right 12 bits)
256236 } page_t;
257237```
258238
259239Pascal:
260240```
261241type
262242 Unsigned_7 = 0 .. (1 shl 7) - 1;
263243 Unsigned_20 = 0 .. (1 shl 20) - 1;
264244
265245 type
266246 page_t = bitpacked record
267247 present : boolean;
268248 rw : boolean;
269249 user : boolean;
270250 accessed : boolean;
271251 dirty : boolean;
272252 unused : Unsigned_7;
273253 frame : Unsigned_20;
274254 end;
275255```
276256
277257# 用 Lua 脚本将 C 转换为 Pascal
278258
279259我对 Lua 脚本语言的强大功能印象深刻,很容易去完成一些有趣的事情。
280260```
281261--
282262 -- Please send any improvement to mingodadATgmailDOTcom.
283263 --
284264
285265 inFileName = arg[1] or 'g:\\tmp\\plua\\clua\\lvm.c'
286266
287267 fh = assert(io.open(inFileName))
288268 cbody = fh:read('*a')
289269 fh:close()
290270
291271 pasbody = cbody
292272
293273 function split(str, pat)
294274 local t = {} -- NOTE: use {n = 0} in Lua-5.0
295275 local fpat = '(.-)' .. pat
296276 local last_end = 1
297277 local s, e, cap = str:find(fpat, 1)
298278 while s do
299279 if s ~= 1 or cap ~= '' then
300280 table.insert(t, cap)
301281 end
302282 last_end = e+1
303283 s, e, cap = str:find(fpat, last_end)
304284 end
305285 if last_end <= #str then
306286 cap = str:sub(last_end)
307287 table.insert(t, cap)
308288 end
309289 return t
310290 end
311291
312292 function trim(s)
313293 -- from PiL2 20.4
314294 return (s:gsub('^%s*(.-)%s*$', '%1'))
315295 end
316296
317297 function trimChars(str, c1, c2)
318298 return str:gsub('^%' .. c1 .. '*(.-)%' .. c2 .. '*$', '%1')
319299 end
320300
321301 function getPascalType(cType)
322302 if cType == 'void' then
323303 return 'pointer'
324304 elseif cType == 'int' then
325305 return 'integer'
326306 elseif cType == 'short' then
327307 return 'Shortint'
328308 elseif cType == 'define' then
329309 return 'is_define'
330310 else
331311 return cType
332312 end
333313 end
334314
335315
336316 --check var name and type
337317 --if var starts with a capital letter
338318 -- add 'T' informt of it
339319 --if var is preceded by * then add a 'P' for type
340320
341321 function checkVarType(aType, aVar)
342322 aType = getPascalType(aType)
343323 aType = aType:gsub('^(%u)', 'T%1')
344324 aVar = aVar:gsub('^(%*)', function(m)
345325 aType = 'P' .. aType
346326 return ''
347327 end)
348328 aVar = aVar:gsub('(%[[^]]+%])', function(m)
349329 aType = 'array' .. m .. ' of ' .. aType
350330 return ''
351331 end)
352332 return aType, aVar
353333 end
354334
355335 function varDeclaration(aType, aVar)
356336 aType, aVar = checkVarType(aType, aVar)
357337 return aVar .. ' : ' .. aType
358338 end
359339
360340 function checkDeclarationOrGoto(m1, m2, m3)
361341 if m2 ~= 'goto' then
362342 return '\n' .. m1 .. varDeclaration(m2, m3) .. ';'
363343 else
364344 return '\n' .. m1 .. m2 .. ' ' .. m3 .. ';'
365345 end
366346 end
367347
368348 function addProcFunc(mtype, mname, mparams, mbody)
369349 local str, isFunc, rType, k, v
370350 if mtype == 'void' then
371351 str = '\nprocedure '
372352 isFunc = false
373353 else
374354 str = '\nfunction '
375355 isFunc = true
376356 end
377357 mtype, mname = checkVarType(mtype, mname)
378358 local vparams = split(trimChars(mparams, '(',')'), ',')
379359 str = str .. mname .. '('
380360
381361 local tparams = {}
382362 for k, v in pairs(vparams) do
383363 local vparam = split(trim(v), ' ')
384364 if #vparam > 2 then
385365 table.insert(tparams, vparam[1] .. ' ' .. varDeclaration(vparam[2], vparam[3]))
386366 else
387367 --print(vparam[1], vparam[2])
388368 table.insert(tparams, varDeclaration(vparam[1], vparam[2] or 'is_define'))
389369 end
390370 end
391371
392372 str = str .. table.concat(tparams, '; ') .. ')'
393373 if isFunc then
394374 if mtype == 'int' then
395375 rType = 'integer'
396376 else
397377 rType = mtype
398378 end
399379 str = str .. ':' .. rType
400380 end
401381
402382 if mbody then
403383 local tblLabels = {}
404384 for v in mbody:gmatch('\n[\t ]*([%w_]+)[\t ]*:[^=]') do
405385 if v ~= 'default' then
406386 table.insert(tblLabels, v)
407387 end
408388 end
409389
410390 if #tblLabels > 0 then
411391 str = str .. ';\nlabel\n '.. table.concat(tblLabels, ', ')
412392 end
413393
414394 local declarations = {}
415395
416396 mbody = mbody:gsub('(\n[\t ]*)const[\t ]+([%w_]+)[\t ]+(%*?[%w_]+)[\t ]*:%=[\t ]*([^;\n]+;)','%1 %2 %3 := %4')
417397
418398 mbody = mbody:gsub('(\n[\t ]*)([%w_]+)[\t ]+(%*?[%w_]+)[\t ]*:%=[\t ]*([^;\n]+;)', function(m1, m2, m3, m4)
419399 table.insert(declarations, varDeclaration(m2, m3) .. ';' )
420400 return m1 .. m3 .. ' := ' .. m4
421401 end)
422402
423403 mbody = mbody:gsub('\n[\t ]*const[\t ]*([%w_]+)[\t ]+(%*?[%w_]+)[\t ]*;', function(m1,m2)
424404 table.insert(declarations, varDeclaration(m1, m2) .. ';')
425405 return ''
426406 end)
427407
428408 mbody = mbody:gsub('\n([\t ]*)([%w_]+)[\t ]+(%*?[%w_ ,]+);', function(m1,m2,m3)
429409 if m2 ~= 'goto' then
430410 table.insert(declarations, varDeclaration(m2, m3) .. ';')
431411 return ''
432412 else
433413 return '\n' .. m1 .. m2 .. ' ' .. m3 .. ';'
434414 end
435415 end)
436416
437417
438418 if #declarations > 0 then
439419 local unique_decl = {}
440420 table.sort(declarations)
441421 local lastV = ''
442422 local k2, v2
443423 for k2,v2 in pairs(declarations) do
444424 if v2 ~= lastV then
445425 lastV = v2
446426 table.insert(unique_decl, v2)
447427 end
448428 end
449429 str = str .. ';\nvar\n '.. table.concat(unique_decl, '\n ') .. '\n'
450430 else
451431 str = str .. ';\n'
452432 end
453433
454434 str = str .. 'begin' .. trimChars(mbody, '{','}') .. 'end'
455435 end
456436 return str .. ';'
457437 end
458438
459439 --*************************************
460440 --
461441 -- Order of substitutions are important
462442 --
463443 --*************************************
464444
465445 --=assignements statements
466446 pasbody = pasbody:gsub("([\t ]*)([%w_]+)[\t ]*=[\t ]*([^=;\n]+);", '%1%2 := %3;')
467447
468448 --return
469449 pasbody = pasbody:gsub('([\t ]*)return[\t ]+([^;]+);', '%1exit(%2);')
470450
471451 --NULL
472452 pasbody = pasbody:gsub('([^%w]+)NULL([^%w]+)', '%1nil%2')
473453
474454 --void functions to procedure declaratios
475455 pasbody = pasbody:gsub('([%w_*]+)[\t ]+([%w_*]+)[\t ]*(%b())[%s]*(%b{})', addProcFunc)
476456 --pasbody = pasbody:gsub('\n([%w_]+)%s+([^%s]+)%s*(%b());', addProcFunc)
477457
478458 --const/static
479459 tblLeaveCommented = {
480460 'const', 'static'
481461 }
482462 for k,v in pairs(tblLeaveCommented) do
483463 pasbody = pasbody:gsub('([\t ]*)(' .. v .. ')([\t ]*)', '%1{%2}%3')
484464 end
485465
486466 --defines to const
487467 isConstEmmited = false
488468 function addConst(m1,m2)
489469 local sm
490470 sm = ''
491471 if not isConstEmmited then
492472 isConstEmmited = true
493473 sm = '\nconst'
494474 end
495475 return sm .. '\n\t' .. m1 .. ' = ' .. m2 .. ';'
496476 end
497477
498478 isConstEmmited = false
499479 pasbody = pasbody:gsub('\n#define%s+([^%s]+)%s+(%b())', '\nconst %1 = %2;')
500480 isConstEmmited = false
501481 pasbody = pasbody:gsub('\n#define%s+([^%s]+)[ \t]+([^%s]+)', '\nconst %1 = %2;')
502482
503483 --includes
504484 tblUses = {}
505485 pasbody = pasbody:gsub('\n#[ \t]*(include)%s+([^\n]+)', function(m1,m2)
506486 for w in m2:gmatch('"([^.]+)%..+"') do
507487 table.insert(tblUses, w)
508488 end
509489 return '\n//#' .. m1 .. ' ' .. m2
510490 end)
511491 pasbody = '//uses ' .. table.concat(tblUses, ', ') .. ';\n' .. pasbody
512492
513493 --defines to compiler directives
514494 pasbody = pasbody:gsub('\n#([^\n]+)', '\n{$%1}')
515495
516496 --comments
517497 pasbody = pasbody:gsub('\n#', '\n//#')
518498 pasbody = pasbody:gsub('/%*', '(*')
519499 pasbody = pasbody:gsub('%*/', '*)')
520500
521501 --declarations
522502 pasbody = pasbody:gsub('\n([\t ]*)([%w_]+)[\t ]+([%w_ ,]+);', checkDeclarationOrGoto)
523503
524504 --structs
525505 function parseStruct(m1, m2)
526506 return '\n' .. m1 .. ' = record\n' .. trimChars(m2, '{', '}') .. '\nend'
527507 end
528508 pasbody = pasbody:gsub('\n[\t ]*struct[\t ]+([%w_]+)[\t ]*(%b{})', parseStruct)
529509
530510 --if statements
531511 parseStatementCalled = false
532512
533513 function parseStatement(mSpace, mStatement, mCond, mBody)
534514 parseStatementCalled = true
535515 local vStatement
536516 if mStatement == 'if' then
537517 vStatement = mStatement .. ' ' .. mCond .. ' then'
538518 elseif mStatement == 'else' then
539519 return mSpace .. mStatement .. ' begin' .. trimChars(mCond, '{', '}') .. ' end;'
540520 elseif (mStatement == 'while') then
541521 vStatement = mStatement .. ' ' .. mCond .. ' do'
542522 elseif (mStatement == 'for') then
543523 vStatement = mStatement .. ' ' .. mCond .. ' do'
544524 --local forArgs = split(trimChars(mCond, '(', ')'), ';')
545525 --return mSpace .. (forArgs[1] or '') .. ';' .. mSpace ..'while (' ..
546526 -- (forArgs[2] or 'true') .. ') do' .. mSpace .. 'begin' .. mSpace .. trimChars(mBody, '{', '}') .. '\n' .. mSpace ..
547527 -- (forArgs[3] or '') .. ';\n' .. mSpace .. 'end;'
548528 else
549529 vStatement = mStatement .. ' ' .. mCond .. '\n'
550530 end
551531 return mSpace .. vStatement .. ' begin' .. trimChars(mBody, '{', '}') .. 'end;'
552532 end
553533
554534 -- for nested blocks
555535 parseStatementCalled = true
556536 while(parseStatementCalled) do
557537 parseStatementCalled = false
558538 pasbody = pasbody:gsub('([^%w_])(if)[\t ]*(%b())[\t ]*(%b{})', parseStatement)
559539 end
560540
561541 -- else
562542 pasbody = pasbody:gsub('([\t ]+)(else)[\t ]*(%b{})', parseStatement)
563543
564544 pasbody = pasbody:gsub("([^%w_])if[\t ]*(%b())[\t ]*([^;\n]+);", '%1if %2 then %3;')
565545
566546 --?: short if
567547 pasbody = pasbody:gsub("([^?])?([^:;\n]):[\t ]*([^%s;]+);", ' iff(%1, %2, %3) ')
568548
569549 --while loop
570550 -- for nested blocks
571551 parseStatementCalled = true
572552 while(parseStatementCalled) do
573553 parseStatementCalled = false
574554 pasbody = pasbody:gsub('([^%w_])(while)[\t ]*(%b())[\t ]*(%b{})', parseStatement)
575555 end
576556
577557 --for loop
578558 -- for nested blocks
579559 parseStatementCalled = true
580560 while(parseStatementCalled) do
581561 parseStatementCalled = false
582562 pasbody = pasbody:gsub('([^%w_])(for)[\t ]*(%b())%s*(%b{})', parseStatement)
583563 end
584564
585565 --do/while
586566 -- for nested blocks
587567 parseStatementCalled = true
588568 while(parseStatementCalled) do
589569 parseStatementCalled = false
590570 pasbody = pasbody:gsub("([^%w_])do[\t ]*(%b{})[\t ]*while([^;\n]+);",
591571 function(m1, m2, m3)
592572 parseStatementCalled = true
593573 return m1 .. 'repeat ' .. trimChars(m2, '{', '}') .. 'until not' .. m3
594574 end)
595575 end
596576
597577
598578 --switch/case statements
599579
600580 --begin/end enclose blocks around
601581 -- for nested blocks
602582 parseStatementCalled = true
603583 while(parseStatementCalled) do
604584 parseStatementCalled = false
605585 pasbody = pasbody:gsub("([^%w_]case[\t ]+[^:]+)[\t ]*:[%s]*(%b{})",
606586 function(m1, m2, m3)
607587 parseStatementCalled = true
608588 return m1 .. ': begin' .. trimChars(m2, '{', '}') .. 'end;'
609589 end)
610590 pasbody = pasbody:gsub("([^%w_]default[\t ]*):[%s]*(%b{})",
611591 function(m1, m2, m3)
612592 parseStatementCalled = true
613593 return m1 .. ': begin' .. trimChars(m2, '{', '}') .. 'end;'
614594 end)
615595 end
616596
617597 --breaks remove
618598 pasbody = pasbody:gsub("([^%w_]case[\t ]+[^:]+)[\t ]*:[%s]*(.-)break;", '%1: %2')
619599
620600 --case
621601 pasbody = pasbody:gsub("([^%w_])case[\t ]+([^:]+):", '%1%2:')
622602
623603 -- for nested blocks
624604 parseStatementCalled = true
625605 while(parseStatementCalled) do
626606 parseStatementCalled = false
627607 pasbody = pasbody:gsub("([^%w_])switch[\t ]*(%b())[\t ]*(%b{})",
628608 function(m1, m2, m3)
629609 parseStatementCalled = true
630610 return m1 .. 'case ' .. m2 .. ' of ' .. trimChars(m3, '{', '}') .. 'end;'
631611 end)
632612 end
633613
634614 --pasbody = pasbody:gsub("([\t ]*)case[\t ]+('.')[\t ]*:\n", '%1%2:\n')
635615 --pasbody = pasbody:gsub("([\t ]*)case[\t ]+(%d+)[\t ]*:\n", '%1%2:\n')
636616 --pasbody = pasbody:gsub("([\t ]*)(case)[\t ]+('.')[\t ]*:[\t ]*(%b{})", '%1%2 : %3')
637617
638618 --pre/pos increments
639619 -- (n)++ -> PosInc(n)
640620 pasbody = pasbody:gsub("(%([^%s+]+%))%+%+", 'PosInc%1')
641621 -- n*++ -> PosInc(n*)
642622 pasbody = pasbody:gsub("([^%s*+]+)%+%+", 'PosInc(%1)')
643623 -- ++(n) -> PreInc(n)
644624 pasbody = pasbody:gsub("%+%+(%([^%s;+]+%))", 'PreInc%1')
645625 -- ++*n -> PreInc(n)
646626 pasbody = pasbody:gsub("%+%+([^%s*;+]+)", 'PreInc(%1)')
647627
648628 -- (n)--
649629 pasbody = pasbody:gsub("(%([^%s-]+%))%-%-", 'PosDec%1')
650630 -- n*--
651631 pasbody = pasbody:gsub("([^%s*-]+)%-%-", 'PosDec(%1)')
652632 -- --(n)
653633 pasbody = pasbody:gsub("%-%-(%([^%s;-]+%))", 'PreDec%1')
654634 -- --n
655635 pasbody = pasbody:gsub("%-%-([^%s;-]+)", 'PreDec(%1)')
656636
657637 --boolean operators
658638 tblBooleanOperators = {
659639 {'||', 'or'},
660640 {'&&', 'and'},
661641 }
662642 for k,v in pairs(tblBooleanOperators) do
663643 pasbody = pasbody:gsub('([\t ]*)' .. v[1] .. '([\t ]*)', '%1) ' .. v[2] .. ' (%2')
664644 end
665645
666646
667647 --pointers
668648 pasbody = pasbody:gsub("%->", '.')
669649 pasbody = pasbody:gsub("%(%*([%w_]+)", '(%1^')
670650 pasbody = pasbody:gsub("%*%*([%w_]+)", '%1^^')
671651 pasbody = pasbody:gsub("&([%w_]+)", '@%1')
672652 pasbody = pasbody:gsub("%*([%w_]+)[\t ]*:[\t ]*([%w_]+);", '%1 : ^%2;')
673653 pasbody = pasbody:gsub("%^char", 'pchar')
674654 --pasbody = pasbody:gsub("%*([%w_]+)[\t ]*:=[\t ]*([^;\n]+);", '%1^ := %2;')
675655
676656 --bit operators
677657 tblBitOperators = {
678658 {'<<', 'shl'},
679659 {'>>', 'shr'},
680660 {'|', 'or'},
681661 {'&', 'and'},
682662 {'~', 'not'},
683663 }
684664
685665 for k,v in pairs(tblBitOperators) do
686666 pasbody = pasbody:gsub('([\t ]*)' .. v[1] .. '([\t ]*)', '%1 ' .. v[2] .. ' %2')
687667 end
688668
689669 --==eq operator
690670 pasbody = pasbody:gsub("([\t ]*)%=%=([\t ]*)", '%1 = %2')
691671
692672 --!= not eq operator
693673 pasbody = pasbody:gsub("([\t ]*)!%=([\t ]*)", '%1 <> %2')
694674
695675 --! unary
696676 pasbody = pasbody:gsub('([\t ]*)!([\t ]*)', '%1 not %2')
697677
698678 --blocks
699679 --pasbody = pasbody:gsub("(%b{})", function(m1) return 'begin' .. trimChars(m1, '{', '}') .. 'end;' end)
700680 --pasbody = pasbody:gsub("(%b{})", function(m1) return 'begin' .. trimChars(m1, '{', '}') .. 'end;' end)
701681
702682 --strings and escaped characters
703683 tblEscapedCahrs = {
704684 {'\\"', '"'},
705685 {'\\\\', '\\'},
706686 {'\\t', "'#9"},
707687 {'\\n', "'#10'"},
708688 {'\\f', "'#12'"},
709689 }
710690 pasbody = pasbody:gsub('%b""', function(m1)
711691 return "'" .. trimChars(m1:gsub("'", "''") , '"', '"') .. "'"
712692 end)
713693 for k,v in pairs(tblEscapedCahrs) do
714694 pasbody = pasbody:gsub(v[1], v[2])
715695 end
716696
717697 --common functions/procedure
718698 tblOrigFuncNewFunc = {
719699 {'printf', 'format'},
720700 {'malloc', 'GetMem'},
721701 {'free', 'Dispose'},
722702 {'memcpy', 'Move'},
723703 }
724704
725705 for k,v in pairs(tblOrigFuncNewFunc) do
726706 pasbody = pasbody:gsub('([\t ]+)' .. v[1] .. '%(', '%1' .. v[2] .. '(')
727707 end
728708
729709 --typedefs
730710 isTypeEmmited = false
731711 function addType(m1,m2)
732712 local sm
733713 sm = ''
734714 if not isTypeEmmited then
735715 isTypeEmmited = true
736716 sm = '\ntype'
737717 end
738718 return sm .. '\n\t' .. m2 .. ' = ' .. m1 .. ';'
739719 end
740720 --pasbody = pasbody:gsub('\ntypedef%s+struct%s+([^%s]+)%s+([^;]+)', addType)
741721 --pasbody = pasbody:gsub('\ntypedef%s+([^%s]+)%s+([^;]-)', addType)
742722 pasbody = pasbody:gsub('\n[\t ]*typedef[\t ]+struct[\t ]+([%w_]+)[\t ]+([^;]+)', '\n%2 = %1')
743723 pasbody = pasbody:gsub('\n[\t ]*typedef[\t ]+struct%s+(%b{})%s+([%w_]+);',
744724 function(m1, m2) return m2 .. ' = record' .. trimChars(m1, '{', '}') .. 'end;' end)
745725
746726
747727 -- print the results
748728 print(pasbody)
749729```
750730
751731以下是转换后的 C 文件示例:
752732```
753733//uses lua, llimits, lmem, lstate, lzio;
754734 (*
755735 ** $Id: lzio.c,v 1.31.1.1 2007/12/27 13:02:25 roberto Exp $
756736 ** a generic input stream interface
757737 ** See Copyright Notice in lua.h
758738 *)
759739
760740
761741 //#include <string.h>
762742
763743 {$define lzio_c}
764744 {$define LUA_CORE}
765745
766746 //#include 'lua.h'
767747
768748 //#include 'llimits.h'
769749 //#include 'lmem.h'
770750 //#include 'lstate.h'
771751 //#include 'lzio.h'
772752
773753
774754
775755 function luaZ_fill(z : PTZIO):integer;
776756 var
777757 L : Plua_State;
778758 buff : Pchar;
779759 size : size_t;
780760 begin
781761 *L := z.L;
782762 lua_unlock(L);
783763 buff := z.reader(L, z.data, @size);
784764 lua_lock(L);
785765 if (buff = nil ) or ( size = 0) then exit(EOZ);
786766 z.n := size - 1;
787767 z.p := buff;
788768 exit(char2int(PosInc^((z.p))));
789769 end;
790770
791771
792772
793773 function luaZ_lookahead(z : PTZIO):integer;
794774 begin
795775 if (z.n = 0) then begin
796776 if (luaZ_fill(z) = EOZ)
797777 exit(EOZ);
798778 else begin
799779 PosInc(z.n); (* luaZ_fill removed first byte; put back it *)
800780 z-PosDec(>p);
801781 end;
802782 end;
803783 exit(char2int(z^.p));
804784 end;
805785
806786
807787
808788 procedure luaZ_init(L : Plua_State; z : PTZIO; reader : lua_Reader; data : Ppointer);
809789 begin
810790 z.L := L;
811791 z.reader := reader;
812792 z.data := data;
813793 z.n := 0;
814794 z.p := nil;
815795 end;
816796
817797
818798 (* --------------------------------------------------------------- read --- *)
819799
820800 function luaZ_read(z : PTZIO; b : Ppointer; n : size_t):size_t;
821801 var
822802 m : size_t;
823803 begin
824804 while (n) do begin
825805 if (luaZ_lookahead(z) = EOZ)
826806 exit(n); (* exit(number of missing bytes *)
827807 m = (n <= z.n) ? n : z.n); (* min. between n and z.n *)
828808 Move(b, z.p, m);
829809 z.n -= m;
830810 z.p += m;
831811 b := (char *)b + m;
832812 n -= m;
833813 end;
834814 exit(0);
835815 end;
836816
837817 (* ------------------------------------------------------------------------ *)
838818
839819 function luaZ_openspace(L : Plua_State; buff : PTMbuffer; n : size_t):Pchar;
840820 begin
841821 if (n > buff.buffsize) then begin
842822 if (n < LUA_MINBUFFER) then n := LUA_MINBUFFER;
843823 luaZ_resizebuffer(L, buff, n);
844824 end;
845825 exit(buff.buffer);
846826 end;
847827```
848828
849829# 人工将 C 头文件转换为 Pascal
850830
851831这时需要同时运用 C 和 Pascal 知识来制作头文件。请参阅以下示例学习转换过程。
852832
853833## 转换常量
854834
855835C:
856836```
857837#define SOME_CONSTANT 5
858838 #define ANOTHER_CONSTANT 6
859839```
860840
861841Pascal:
862842```
863843const
864844 SOME_CONSTANT = 5;
865845 ANOTHER_CONSTANT = 6;
866846```
867847
868848## 转换已声明的函数
869849
870850绝大部分普通函数可以转换如下:
871851
872852C:
873853```
874854int somekind_of_method(int* param_first, int* param_second)
875855 void another_method(char*)
876856```
877857
878858Pascal:
879859```
880860uses ctypes;
881861
882862 const
883863 MyLib = 'mylib';
884864
885865 function somekind_of_method(param_first, param_second: pcint): cint; external MyLib;
886866 procedure another_method_renamed(param1: PChar); external MyLib name 'another_method';
887867```
888868
889869首先请注意,应采用 ctypes 单元及其声明的类型来转换 C 头文件,不要直接采用 Pascal 基础类型。这样可以确保在所有平台上都能正确转换,因为 C 类型在不同架构和操作系统中可能会有不同的长度。
890870
891871其次请注意,基础类型的 C 指针可以转换为 ctypes 中声明的类型,例如 int* 是 C int 型的指针,所以可转换为 pcint 类型(指向 C 整数的指针)。C int 可以转换为 cint,并且在 Pascal 中可以简化同类型参数的声明:“param_first, param_second: pcint”。
892872
893873最后请注意,如果返回值为 **void** ,应该将函数替换成过程。
894874
895875[创建 C 到 Pascal 的对应关系](<https://github.com/williamhunter/pascal-bindings-for-c>) 是带有源代码的教程,详细介绍了如何对 C 代码库进行人工转换,处理各种数据类型(字符串、数组等)。该教程还演示了如何用 MinGW C 编译器创建静态(*.a)和共享/动态库(*.so 或 *.dll)。再结合使用 h2pas 即非常有效。
896876
897877请参阅参考手册中的[外部函数](<http://www.freepascal.org/docs-html/ref/refse85.html>)。
898878
899879# 在 Lazarus-CCR 或 Free Pascal 发布绑定代码
900880
901881绑定代码可提交至 Lazarus CCR 库(参见 [[Using the Lazarus-ccr SVN repository]]),以供其他人使用和维护。如果这些绑定代码可跨平台应用,还可能会纳入 FreePascal 发行版中。
902882
903883# 参阅
904884
905885 * G. Marcou, E. Engler, A. Varnek, _How to use C code in Free Pascal projects_ , Université de Strasbourg, 2009, [Link 1](<http://ftp.psu.ru/programming/fpc/docs-pdf/CinFreePascal.pdf>), [Link 2](<https://www.scribd.com/document/370417404/CinFreePascal-pdf>), 简述:如何在 Free Pascal 中使用 C 和 C++ 代码的简短教程,包括编写封装代码。
906886 * [另一教程](<https://github.com/williamhunter/pascal-bindings-for-c/blob/master/docs/Creating%20Pascal%20bindings%20for%20C%20\(v1.0\).pdf>)演示了如何使用面向对象的 C 语言代码和库。
907887 * [[Common problems when converting C header files|转换 C 语言头文件的常见问题]]
908888 * [[Pascal for C users|C 语言用户的 Pascal 说明]]
909889 * [[Lazarus/FPC Libraries]]
910890 * [[SWIG]]
911891
912892---
913893*From the Free Pascal wiki, page "Creating bindings for C libraries/zh CN", as the Internet Archive kept it on 2025-10-04, last changed on 2024-09-22. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history