MATLAB: How to make codegen concatenate strings

codegenmatlab coderstrcat

Using R2012a codegen, if I create the following m file:
function testStrCat()
path = char(zeros(1, 40));
fspec = char(zeros(1, 132));
coder.ceval('strcat', path, 'path');
coder.ceval('strcat', fspec, path);
coder.ceval('strcat', fspec, '/');
then build it as a C static library, I get the following output file:
1 /*
2 * testStrCat.c
3 *
4 * Code generation for function 'testStrCat'
5 *
6 * C source code generated on: Thu Oct 04 13:47:50 2012
7 *
8 */
9
10 /* Include files */
11 #include "rt_nonfinite.h"
12 #include "testStrCat.h"
13
14 /* Type Definitions */
15
16 /* Named Constants */
17
18 /* Variable Declarations */
19
20 /* Variable Definitions */
21
22 /* Function Declarations */
23
24 /* Function Definitions */
25
26 /*
27 * function testStrCat
28 */
29 void testStrCat(void)
30 {
31 char_T cv0[40];
32 int32_T i0;
33 char_T cv1[4];
34 static const char_T cv2[4] = { 'p', 'a', 't', 'h' };
35
36 char_T cv3[132];
37
38 /* 'testStrCat:2' path = char(zeros(1, 40)); */
39 /* 'testStrCat:3' fspec = char(zeros(1, 132)); */
40 /* 'testStrCat:5' coder.ceval('strcat', path, 'path'); */
41 for (i0 = 0; i0 < 40; i0++) {
42 cv0[i0] = '\x00';
43 }
44
45 for (i0 = 0; i0 < 4; i0++) {
46 cv1[i0] = cv2[i0];
47 }
48
49 strcat(cv0, cv1);
50
51 /* 'testStrCat:6' coder.ceval('strcat', fspec, path); */
52 for (i0 = 0; i0 < 132; i0++) {
53 cv3[i0] = '\x00';
54 }
55
56 for (i0 = 0; i0 < 40; i0++) {
57 cv0[i0] = '\x00';
58 }
59
60 strcat(cv3, cv0);
61
62 /* 'testStrCat:7' coder.ceval('strcat', fspec, '/'); */
63 for (i0 = 0; i0 < 132; i0++) {
64 cv3[i0] = '\x00';
65 }
66
67 strcat(cv3, '/');
68
69 /* coder.ceval('strcat', fspec, file); */
70 }
71
72 /* End of code generation (testStrCat.c) */
Notice that each time I try to concatenate a string, it zeros out the destination string first. Am I doing this wrong?
Thanks Sean

Best Answer

I think you'll get closer to what you want by using the right MATLAB Coder directives:
function testStrCat()
path = coder.nullcopy(char(zeros(1, 40)));
fspec = coder.nullcopy(char(zeros(1, 132)));
coder.ceval('strcat', coder.ref(path), ['path' 0]); %null-termination
coder.ceval('strcat', coder.ref(fspec), path);
coder.ceval('strcat', coder.ref(fspec), '/');
Now the code looks like:
void testStrCat(void)
{
char_T path[40];
char_T fspec[132];
char_T cv0[5];
int32_T i0;
static const char_T cv1[5] = { 'p', 'a', 't', 'h', '\x00' };
for (i0 = 0; i0 < 5; i0++) {
cv0[i0] = cv1[i0];
}
strcat(path, cv0);
strcat(fspec, path);
strcat(fspec, '/');
}
I don't know how you can avoid that extra copy for the string "path".