I just started using dlls, but I haven't had this problem before, so it might not be dll connected. I am have KMP String-match algorithm implemented in c++ and I am calling it from c# using dll.
This is my export:
extern "C" __declspec (dllexport) const char* naive(const char* text, const char* str);
extern "C" __declspec (dllexport) const char* KMP(const char* text, const char* str);
My import:
[DllImport(@"dll_path", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr KMP([MarshalAs(UnmanagedType.LPStr)] string text, [MarshalAs(UnmanagedType.LPStr)] string str);
Calling from c#
string output = Marshal.PtrToStringAnsi(KMP(richTextBox1.Text, richTextBox2.Text));
And the c++ function:
const char* KMP(const char* text, const char* str)
{
int tL = strlen(text);
int sL = strlen(str);
/* Algorithm */
}
The exception is thrown right after the function is called. So I figured it's not the code implementation. The wired thing is it's only thrown when there is a '\n' new line in the second parameter (str), no matter where exactly. If there are no new lines it runs normally. The thing that confuses me the most is why just the second argument, both are identically declared and used. I also have implemented Naive algorithm, same story.
All the answers I found were only when a negative number was given as size to an array or an undeclared variable, but nothing on pointers. But I doubt it's anything similar, because when my search string (2nd parameter (str)) doesn't contain new line the code executes normally.
Any ideas ?
Thank you in front.
EDIT (body of function):
const char* KMP(const char* text, const char* str)
{
int tL = strlen(text);
int sL = strlen(str);
string match = "";
if (sL == 0 || tL == 0)
throw "both text and string must be larger than 0";
else if (sL > tL)
throw "the text must be longer than the string";
int tI = 0;
int col = 0, row = 0;
while (tI <= tL - sL)
{
int i = 0;
int tmpCol = -1;
int next = 1;
for (; i <= sL && text[i + tI] != '\0'; i++)
{
if (text[i + tI] == '\n')
{
row++;
tmpCol++;
}
if (text[i + tI] == str[0] && next == 1 && i > 0)
next = i;
if (text[i + tI] != str[i])
break;
}
if (i == sL)
{
match += to_string(row) + ',' + to_string(col) + ';';
}
tI += next;
col = tmpCol > -1 ? tmpCol : col + next;
}
char* c = new char[match.length() - 1];
c[match.length() - 1] = '\0';
for (int i = 0; i < match.length() - 1; i++)
c[i] = match[i];
return c;
}