[英]automating header file manipulation C/C++ -> C#
我正在使用Matlab編碼器生成一些C代碼,然后最終由VS 2010中的C#應用程序使用。為了做到這一點,我必須手動更改以下文件的某些頭文件(即正在使用的“接口”) :
#ifdef __cplusplus
extern "C" {
#endif
extern real_T add(real_T a, real_T b);
#ifdef __cplusplus
}
#endif
#endif
至
#ifdef __cplusplus
extern "C" {
#endif
extern __declspec(dllexport) add(real_T a, real_T b);
#ifdef __cplusplus
}
#endif
#endif
如果在重新生成C代碼后必須對多個頭文件執行此操作,這可能會非常繁瑣。 有沒有簡單的方法可以自動化該過程?
請注意,我不是C / C ++程序員。 由於某些其他要求,C / C ++代碼僅用作“中間中介”。 任何反饋都非常歡迎。
PS:
請注意,我主要是在尋找Visual Studio 2010解決方案(宏?)。 我總是可以編寫一些C#/ Matlab程序來實現所有這些功能,但是我覺得這太過分了。
在MATLAB中,您可以使用regexprep
-by-regular-expression( regexprep
):
% This is obtained by textscan() or load() or similar.
haystack = {
'#ifdef __cplusplus'
'extern "C" {'
'#endif'
'extern real_T add(real_T a, real_T b);'
'#ifdef __cplusplus'
'}'
'#endif'
'#endif'
};
% Search query
needle = '^extern\s*real_T\s*add\(real_T\s*a,\s*real_T\s*b\).*$'
% Replacement
pin = 'extern __declspec(dllexport) real_T add(real_T a, real_T b);';
% Replace all needles with pins
C = regexprep(haystack, needle, pin);
這個特殊的needle
還發現所有語句之間具有任意數量的空格的出現。 您可以將其更改為
needle = '^extern\s*real_T\s*add\(real_T\s*\w*,\s*real_T\s*\w*\).*$'
如果每個標題中的名稱a
和b
也可以不同。
請注意,這可以在循環內完成,在循環中,循環遍歷由dir('*.h')
或類似文件獲取的所有文件,並且每次迭代都通過textscan()
或類似文件加載新的haystack
。 像這樣:
% all relevant files
files = dir('*.h');
% Loop over all files
for ii = 1:numel(files)
% Load the file
fid = fopen(files(ii).name, 'r');
haystack = textscan(fid, '%s', 'Delimiter', '\n');
haystack = haystack{1};
fclose(fid);
% do the replacement here
% ...
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.